给定一个标题和一个最大长度,什么是缩短标题的最佳方法?以下是我的想法:
def shorten_title(title, max_length):
if len(title) > max_length:
split_title = title.split()
length = len(title)
n = 1
while length > max_length:
shortened_title = split_title[:length(split_title)-n]
n+=1
return shortened_title
else:
return title
试试看:)
如果你只需要打破一个空间,那就足够了。另外,还有一些关于更复杂方法的文章,比如:Truncate a string without ending in the middle of a word。在
更新来自okm的地址注释:
要处理边缘情况,例如在max_length之前找不到空格,请显式处理:
^{pr2}$那怎么样?在
好吧,不用分词,你需要这样:
^{pr2}$以下是我看到的结果:
我试图保持代码和逻辑与原始海报相似,但肯定有更多的Python式的方法来做到这一点。在
相关问题 更多 >
编程相关推荐