我想以类似于 .split()
的方式分割字符串(因此结果为列表),但更加智能:我希望将其分成最多15个字符的块,但不要在单词中间分割,例如:
string = 'A string with words'
[splitting process takes place]
list = ('A string with','words')
在这个例子中,字符串被分成了'with'和'words'两部分,因为这是你可以进行分割的最后一个位置,并且第一部分少于15个字符。
我想以类似于 .split()
的方式分割字符串(因此结果为列表),但更加智能:我希望将其分成最多15个字符的块,但不要在单词中间分割,例如:
string = 'A string with words'
[splitting process takes place]
list = ('A string with','words')
>>> import textwrap
>>> string = 'A string with words'
>>> textwrap.wrap(string,15)
['A string with', 'words']
>>> 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']
- Dave Costas = 'A string with supercalifragilistic words' textwrap.wrap(s,15) ['A string with s', 'upercalifragili', 'stic words'] re.findall(r'\b.{1,15}\b', s) ['A string with ', ' words']
你可能想要使用正则表达式。Python re 模块有一个 split
函数,但我认为你最好通过匹配组来实现。
>>> re.findall(r'(.{,15})\s(.*$)', 'A string wth words')
[('A string wth', 'words')]
[编辑] 抱歉,我错过了您想要多个块的要点。我本来想在这里放置一个更复杂的正则表达式,但上面提到的textwrap模块就是为此而设计的。如果您选择,我将把扩展正则表达式作为一项练习留给您。