質問

このように、あまりにも長すぎる場合は切り捨てられるタイトルを取得する方法を見つけたいと思います。

'this is a title'
'this is a very long title that ...'

Makoで文字列を印刷し、特定の数の文字よりも大きい場合は「...」で自動的に切り捨てられる方法はありますか?

ありがとう。

役に立ちましたか?

解決

基本的なPythonソリューション:

MAXLEN = 15
def title_limit(title, limit):
    if len(title) > limit:
        title = title[:limit-3] + "..."
    return title

blah = "blah blah blah blah blah"
title_limit(blah) # returns 'blah blah bla...'

これはスペースのみをカットします(可能であれば)

def find_rev(str,target,start):
    str = str[::-1]
    index = str.find(target,len(str) - start)
    if index != -1:
        index = len(str) - index
    return index

def title_limit(title, limit):
    if len(title) <= limit: return title
    cut = find_rev(title, ' ', limit - 3 + 1)
    if cut != -1:
        title = title[:cut-1] + "..."
    else:
        title = title[:limit-3] + "..."
    return title

print title_limit('The many Adventures of Bob', 10) # The...
print title_limit('The many Adventures of Bob', 20) # The many...
print title_limit('The many Adventures of Bob', 30) # The many Adventures of Bob

他のヒント

webhelpers Makoテンプレートと手をつないで行きます。使用する webhelpers.text.truncate - http://sluggo.scrapping.cc/python/webhelpers/modules/text.html#webhelpers.text.truncate

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top