Python中是否有一个函数可以在不忽略空格的情况下拆分字符串?
时间:2020-03-06 14:31:37 来源:igfitidea点击:
Python中是否有一个函数可以在不忽略结果列表中的空格的情况下拆分字符串?
例如:
s="This is the string I want to split".split()
给我
>>> s ['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']
我想要类似的东西
['This',' ','is',' ', 'the',' ','string', ' ', .....]
解决方案
我们尝试做的困难的部分是我们没有给它一个角色来分裂。 split()在提供给它的字符上爆炸一个字符串,并删除该字符。
也许这可能会有所帮助:
s = "String to split" mylist = [] for item in s.split(): mylist.append(item) mylist.append(' ') mylist = mylist[:-1]
凌乱,但它会帮你的忙...
>>> 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")