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

9 投票
3 回答
3680 浏览
提问于 2025-04-15 21:30

我想把一个字符串分割成类似于 .split() 这样得到一个列表,但我希望分割得更聪明一些:我想把它分成每段最多15个字符的块,但不能在单词中间分割。

string = 'A string with words'

[splitting process takes place]

list = ('A string with','words')

在这个例子中,字符串是在 'with' 和 'words' 之间分开的,因为这是最后一个可以分割的地方,并且前面的部分不超过15个字符。

3 个回答

1

你可能想用正则表达式。Python的re模块里有一个split函数,但我觉得你直接用匹配组会更好。

>>> re.findall(r'(.{,15})\s(.*$)', 'A string wth words')
[('A string wth', 'words')]

[编辑] 抱歉,我没注意到你想要多个部分。我本来想在这里放一个更复杂的正则表达式,但上面提到的textwrap模块就是为这个设计的。如果你愿意,可以自己尝试扩展正则表达式。

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']

注意一下在处理空格时的细微差别。

30
>>> import textwrap
>>> string = 'A string with words'
>>> textwrap.wrap(string,15)
['A string with', 'words']

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答