Is there a function in Python to split a string without ignoring the spaces in the resulting list?
Python中是否有一个函数来分割字符串而不忽略结果列表中的空格?
E.g:
s="This is the string I want to split".split()
gives me
>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']
I want something like
我想要类似的东西
['This',' ','is',' ', 'the',' ','string', ' ', .....]
4 个解决方案
#1
40
>>> import re
>>> re.split(r"(\s+)", "This is the string I want to split")
['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split']
Using the capturing parentheses in re.split() causes the function to return the separators as well.
在re.split()中使用捕获括号会导致函数返回分隔符。
#2
4
I don't think there is a function in the standard library that does that by itself, but "partition" comes close
我不认为标准库中有一个功能可以单独执行,但“分区”接近
The best way is probably to use regular expressions (which is how I'd do this in any language!)
最好的方法可能是使用正则表达式(这就是我用任何语言执行此操作的方式!)
import re
print re.split(r"(\s+)", "Your string here")
#3
2
Silly answer just for the heck of it:
愚蠢的回答只是为了它的哎呀:
mystring.replace(" ","! !").split("!")
#4
1
The hard part with what you're trying to do is that you aren't giving it a character to split on. split() explodes a string on the character you provide to it, and removes that character.
你要做的事情的难点在于你没有给它一个角色来分裂。 split()会在您提供给它的字符上展开一个字符串,并删除该字符。
Perhaps this may help:
也许这可能有所帮助:
s = "String to split"
mylist = []
for item in s.split():
mylist.append(item)
mylist.append(' ')
mylist = mylist[:-1]
Messy, but it'll do the trick for you...
凌乱,但它会为你做的伎俩......
#1
40
>>> import re
>>> re.split(r"(\s+)", "This is the string I want to split")
['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split']
Using the capturing parentheses in re.split() causes the function to return the separators as well.
在re.split()中使用捕获括号会导致函数返回分隔符。
#2
4
I don't think there is a function in the standard library that does that by itself, but "partition" comes close
我不认为标准库中有一个功能可以单独执行,但“分区”接近
The best way is probably to use regular expressions (which is how I'd do this in any language!)
最好的方法可能是使用正则表达式(这就是我用任何语言执行此操作的方式!)
import re
print re.split(r"(\s+)", "Your string here")
#3
2
Silly answer just for the heck of it:
愚蠢的回答只是为了它的哎呀:
mystring.replace(" ","! !").split("!")
#4
1
The hard part with what you're trying to do is that you aren't giving it a character to split on. split() explodes a string on the character you provide to it, and removes that character.
你要做的事情的难点在于你没有给它一个角色来分裂。 split()会在您提供给它的字符上展开一个字符串,并删除该字符。
Perhaps this may help:
也许这可能有所帮助:
s = "String to split"
mylist = []
for item in s.split():
mylist.append(item)
mylist.append(' ')
mylist = mylist[:-1]
Messy, but it'll do the trick for you...
凌乱,但它会为你做的伎俩......