在空格之后拆分字符串

时间:2017-02-01 23:25:00

标签: python string python-3.x split

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

foo bar hello world

因此输出将是一个列表:

['foo ', 'bar ', 'hello ', 'world ']

2 个答案:

答案 0 :(得分:8)

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

{{1}}

答案 1 :(得分:6)

只需在空白处拆分,然后重新添加它们。

a = 'foo bar hello world'

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

splitted = [x + ' ' for x in splitted]  # add the ' ' at the end

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

splitted = ['{} '.format(item) for item in a.split()]
相关问题