11

Python 中是否有内置函数或标准库中的函数,用于将字符串限制为一定长度,如果超出长度,则在其后附加三个点 (...)?

例如:

>>> hypothetical_cap_function("Hello, world! I'm a string", 10)
“你好, ...”
>>> hypothetical_cap_function("你好,世界!我是一个字符串", 20)
“你好,世界!我是……”
>>> hypothetical_cap_function("你好,世界!我是一个字符串", 50)
“你好,世界!我是一个字符串”
4

2 回答 2

20
def cap(s, l):
    return s if len(s)<=l else s[0:l-3]+'...'
于 2012-07-22T17:24:39.727 回答
1

可能最灵活(不只是切片)的方法是创建一个包装器,textwrap.wrap例如:(但请记住,它确实会尝试在某些可能无法得到您所追求的结果的地方进行智能拆分 - 但是这是一个方便了解的模块)

def mywrap(string, length, fill=' ...'):
    from textwrap import wrap
    return [s + fill for s in wrap(string, length - len(fill))]

s = "Hello, world! I'm a string"
print mywrap(s, 10)
# ['Hello, ...', 'world! ...', "I'm a ...", 'string ...']

然后就拿你所追求的元素。

于 2012-07-22T17:33:08.460 回答