Python 在空格后拆分字符串
在Python3.x中,如何拆分如下字符串:Python 在空格后拆分字符串,python,string,python-3.x,split,Python,String,Python 3.x,Split,在Python3.x中,如何拆分如下字符串: foo bar hello world 因此,输出将是如下列表: ['foo ', 'bar ', 'hello ', 'world '] 只需在空白处拆分,然后重新添加 a = 'foo bar hello world' splitted = a.split() # split at ' ' splitted = [x + ' ' for x in splitted] # add the ' ' at the end 或者,如果您想让
foo bar hello world
因此,输出将是如下列表:
['foo ', 'bar ', 'hello ', 'world ']
只需在空白处拆分,然后重新添加
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()]
如果要处理和保留任意运行的空白,则需要正则表达式:
>>> import re
>>> re.findall(r'(?:^|\S+)\s*', ' foo \tbar hello world')
[' ', 'foo \t', 'bar ', 'hello ', 'world']
这是否也适用于多个空格,即插入正确数量的空格?这使得字符串应该拆分的位置不明确。在第一次、第二次、最后一次之后?考虑到他没有具体说明这些信息(在给出示例时我也没有考虑),我认为这没有必要。@RadLexus:不,不会的。像这样简单地使用纯字符串方法是不可能保留任意空格的。这很有用,我会记住这个解决方案,但我不需要保留额外的空格。