如果你有一段非常长的字符串,而你想限制这个字符串的长度。例如:

  1. I want to say hello to you, because you are my world.

你希望只显示前几个单词,多余的单词用省略号表示,变成:

  1. I want to say hello...

那么你可能会这样写:

  1. a = 'I want to say hello to you, because you are my world.'

  2. b = a[:20] + '...'

但是这样的写法并不Pythonic,而且单词会被拆开。因为Python有一个模块,专门用来处理这种需求:

  1. import textwrap

  2. a = 'I want to say hello to you, because you are my world.'

  3. print(textwrap.shorten(a, width=22, placeholder='...')