按字符数将文本拆分为行

pro*_*ach 5 python string

我有一些文字例如:

'This is a line of text over 10 characters'
Run Code Online (Sandbox Code Playgroud)

除非我需要(例如包含超过10个字符的工作的行),否则我需要将其分成不超过10个字符的行而不会破坏单词.

上面的一行会变成:

'This is a\nline of\ntext over\n10\ncharacters'
Run Code Online (Sandbox Code Playgroud)

这是一个相当简单的问题,但我想听听人们会怎么做.我将开始编码并在一段时间内发布我的解决方案.

Sil*_*ost 16

你需要 textwrap

>>> import textwrap
>>> s = 'This is a line of text over 10 characters'
>>> textwrap.fill(s, width=10)
'This is a\nline of\ntext over\n10\ncharacters'
Run Code Online (Sandbox Code Playgroud)