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

例如:

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

最佳答案

def cap(s, l):
    return s if len(s)<=l else s[0:l-3]+'...'

关于用于将字符串限制为最大长度的 Python 函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11602386/

10-15 08:55