python Python中是否有一个函数可以在不忽略空格的情况下拆分字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/113534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 19:31:00  来源:igfitidea点击:

Is there a function in Python to split a string without ignoring the spaces?

pythonsplit

提问by gath

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', ' ', .....]

回答by Greg Hewgill

>>> 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() 中使用捕获括号会导致函数也返回分隔符。

回答by Mez

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")

回答by Foon

Silly answer just for the heck of it:

愚蠢的回答只是为了它:

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

回答by rossp

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...

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