gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:28:51 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com