将第 return 行添加到文本块中,但不要打断单词
Add line return to a block of text, but don't break words
我有一个很长的字符串,例如:
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 个字母,那很好。有谁知道对此的智能解决方案?
使用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...']
我有一个很长的字符串,例如:
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 个字母,那很好。有谁知道对此的智能解决方案?
使用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...']