在空格之后拆分字符串

gus*_*g21 2 python string split python-3.x

在Python 3.x中,我将如何拆分这样的字符串:

foo bar hello world
Run Code Online (Sandbox Code Playgroud)

所以输出将是一个列表,如:

['foo ', 'bar ', 'hello ', 'world ']
Run Code Online (Sandbox Code Playgroud)

Sha*_*ger 8

如果要处理和保留任意空格运行,则需要一个正则表达式:

>>> import re
>>> re.findall(r'(?:^|\S+)\s*', '   foo \tbar    hello world')
['   ', 'foo \t', 'bar    ', 'hello ', 'world']
Run Code Online (Sandbox Code Playgroud)


MSe*_*ert 6

只需在空格处拆分,然后再将它们添加回来.

a = 'foo bar hello world'

splitted = a.split()  # split at ' '

splitted = [x + ' ' for x in splitted]  # add the ' ' at the end
Run Code Online (Sandbox Code Playgroud)

或者如果你想要它更有趣:

splitted = ['{} '.format(item) for item in a.split()]
Run Code Online (Sandbox Code Playgroud)

  • 这使得字符串应该被拆分的地方不明确.在第一,第二,最后?鉴于他没有指明这些信息(我没有考虑到这个例子)我不认为这是必要的. (2认同)