将行返回添加到文本块,但不要破坏单词

时间:2015-01-23 19:44:34

标签: python string line

我有一个很长的字符串,如:

mystring = 'It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness...'''

我想每20个字母插入一次换行符。除了我不想将一个单词分成两半,所以如果它分成22个字母,那很好。有谁知道这个的智能解决方案?

1 个答案:

答案 0 :(得分:4)

使用textwrap

>>> mystring = 'It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness...'''
>>> import textwrap
>>> textwrap.wrap(mystring, width=20)
['It was the best of', 'times, it was the', 'worst of times, it', 'was the age of', 'wisdom, it was the', 'age of', 'foolishness...']