我有一个很长的字符串,例如:
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...']
我是一名优秀的程序员,十分优秀!