[英]Split string just after space
In Python 3.x, how would I split a string like this: 在Python 3.x中,我将如何拆分这样的字符串:
foo bar hello world
So the output would be a list like: 所以输出将是一个列表,如:
['foo ', 'bar ', 'hello ', 'world ']
If you want to handle and preserve arbitrary runs of whitespace, you'll need a regular expression: 如果要处理和保留任意空格运行,则需要一个正则表达式:
>>> import re
>>> re.findall(r'(?:^|\S+)\s*', ' foo \tbar hello world')
[' ', 'foo \t', 'bar ', 'hello ', 'world']
Just split at whitespaces and then add them back again. 只需在空格处拆分,然后再将它们添加回来。
a = 'foo bar hello world'
splitted = a.split() # split at ' '
splitted = [x + ' ' for x in splitted] # add the ' ' at the end
Or if you want it a bit more fancy: 或者如果你想要它更有趣:
splitted = ['{} '.format(item) for item in a.split()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.