考虑字符串
s =“你永远不会知道真相”
如果我想将此字符串拆分为 15 个字符 (s[:15]
),我会得到“you'll never kn”
我想用这个新字符串做的只是提取完整单词(在本例中为“youll”和“never”),然后返回该字符串,以及我的方法循环从不完整单词的开头开始。知道如何做到这一点吗?
编辑:正如 PM 2Ring 所提到的,我目前只关心充当单词分隔符的空格。一旦我弄清楚了,我将处理逗号、连字符、换行符等。
提前致谢!
最佳答案
您可以使用标准库的textwrap
模块。
import textwrap
s = "you'll never know the truth, said the artificially emlengthened example string"
for chunk in textwrap.wrap(s, 15):
print(chunk)
输出
you'll never
know the truth,
said the
artificially
emlengthened
example string
关于Python:如何仅提取x个字符的字符 block 中的完整单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50898184/