使用空格分隔符和最大长度拆分字符串

chr*_*ism 9 python string split

我想以类似的方式分割一个字符串.split()(因此产生一个列表),但是以一种更聪明的方式:我希望它将它拆分成最多15个字符的块,但不会拆分中间字所以:

string = 'A string with words'

[splitting process takes place]

list = ('A string with','words')
Run Code Online (Sandbox Code Playgroud)

此示例中的字符串分为"with"和"words",因为这是您可以拆分它的最后一个位置,第一个位是15个字符或更少.

gho*_*g74 29

>>> import textwrap
>>> string = 'A string with words'
>>> textwrap.wrap(string,15)
['A string with', 'words']
Run Code Online (Sandbox Code Playgroud)


jem*_*nch 6

您可以通过以下两种方式执行此操作

>>> import re, textwrap
>>> s = 'A string with words'
>>> textwrap.wrap(s, 15)
['A string with', 'words']
>>> re.findall(r'\b.{1,15}\b', s)
['A string with ', 'words']
Run Code Online (Sandbox Code Playgroud)

注意空间处理的细微差别.