我有一个很长的字符串,如:
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个字母,那很好。有谁知道这个的智能解决方案?
答案 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...']