Python中是否有一个函数来分割字符串而不忽略结果列表中的空格?

E.g:

s="This is the string I want to split".split()

给了我

>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']

我想要像

这样的东西
['This',' ','is',' ', 'the',' ','string', ' ', .....]
有帮助吗?

解决方案

>>> import re
>>> re.split(r"(\s+)", "This is the string I want to split")
['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split']

使用re.split()中的捕获括号会导致函数返回分隔符。

其他提示

我不认为标准库中有一个功能可以单独执行,但“分区”是指。接近

最好的方法可能就是使用正则表达式(这就是我在任何语言中的表达方式!)

import re
print re.split(r"(\s+)", "Your string here")

愚蠢的回答只是因为它的原因:

mystring.replace(" ","! !").split("!")

你要做的事情的困难部分在于你没有给它一个角色来分裂。 split()在你提供给它的角色上爆炸一个字符串,并删除那个角色。

也许这可能会有所帮助:

s = "String to split"
mylist = []
for item in s.split():
    mylist.append(item)
    mylist.append(' ')
mylist = mylist[:-1]

凌乱,但它会为你做伎俩...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top