Python 截断mako模板中的字符串
如果标题太长,我想找到一种方法将其截断,如下所示:Python 截断mako模板中的字符串,python,pylons,mako,Python,Pylons,Mako,如果标题太长,我想找到一种方法将其截断,如下所示: '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] + "...
'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(目标,len(str)-start)
如果索引!=-1:
索引=len(str)-索引
回报指数
def标题_限制(标题,限制):
如果len(title)webhelpers
与MAKO模板齐头并进。使用webhelpers.text.truncate
-
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