在Python中是否有一个函数来分割字符串而不忽略空格?
问题描述:
是否有Python中的函数来分割字符串而不忽略结果列表中的空格?在Python中是否有一个函数来分割字符串而不忽略空格?
如:
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捕获括号()会导致功能还要返回分隔符。
答
困难的部分与你正在试图做的是什么,你是不是给它一个角色分裂。 split()分解您提供给它的字符上的一个字符串,并删除该字符。
或许,这可能会有帮助:
s = "String to split"
mylist = []
for item in s.split():
mylist.append(item)
mylist.append(' ')
mylist = mylist[:-1]
凌乱,但它会做的伎俩你...
答
我不认为这是在做,通过自身的标准库中的函数,而是“分区”接近
最好的办法可能是使用正则表达式(这是我怎么会做这在任何语言)
import re
print re.split(r"(\s+)", "Your string here")
答
傻回答只是为了它赫克:
mystring.replace(" ","! !").split("!")
与不会在年底有一个额外的空间... – Mez 2008-09-22 08:38:01
我刚刚更新了此代码到r放弃最后的空间。这就是说,它仍然不是最好的方式,只是*一种方法:) – rossp 2008-09-24 03:37:24