python - 在文本 block 中添加换行,但不要打断单词

标签 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 个字母,那很好。有谁知道对此的智能解决方案?

最佳答案

使用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...']

关于python - 在文本 block 中添加换行,但不要打断单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28117550/

相关文章:

algorithm - 查找点,距离和线上所有其他点的总和是最低的

python - 从 pandas 数据框中的地址中删除分数

python - 如何将字典转换为数据框,并将值作为标题和行?

regex - 2 模式字符串匹配算法

C++ 将字符串写入文件 = 额外字节

string - 带格式的 Scala 字符串插值,如何更改语言环境?

python - 使用某些 OpenCV 函数时出现段错误

python - 如何限制使用GeoPandas读取的特征数量?

Python pdb——如何更改 "l"命令列出的默认行?

html - 在 HTML5 canvas 上点两下鼠标画一条线?