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)
如果要处理和保留任意空格运行,则需要一个正则表达式:
>>> import re
>>> re.findall(r'(?:^|\S+)\s*', ' foo \tbar hello world')
[' ', 'foo \t', 'bar ', 'hello ', 'world']
Run Code Online (Sandbox Code Playgroud)
只需在空格处拆分,然后再将它们添加回来.
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)