gpt4 book ai didi

python - 截断 Mako 模板中的字符串

转载 作者:行者123 更新时间:2023-12-01 06:14:42 25 4
gpt4 key购买 nike

我想找到一种方法来截断标题(如果太长),如下所示:

'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

关于python - 截断 Mako 模板中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3918097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com