如果你有一段非常长的字符串,而你想限制这个字符串的长度。例如:
-
I want to say hello to you, because you are my world.
你希望只显示前几个单词,多余的单词用省略号表示,变成:
-
I want to say hello...
那么你可能会这样写:
-
a = 'I want to say hello to you, because you are my world.'
-
b = a[:20] + '...'
但是这样的写法并不Pythonic,而且单词会被拆开。因为Python有一个模块,专门用来处理这种需求:
-
import textwrap
-
a = 'I want to say hello to you, because you are my world.'
-
print(textwrap.shorten(a, width=22, placeholder='...')