仅按python中的第一个空格拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30636248/
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
Split a string only by first space in python
提问by bazinga
I have string for example: "238 NEO Sports"
. I want to split this string only at the firstspace. The output should be ["238","NEO Sports"]
.
我有字符串,例如:"238 NEO Sports"
. 我只想在第一个空格处拆分此字符串。输出应该是["238","NEO Sports"]
.
One way I could think of is by using split()
and finally merging the last two strings returned. Is there a better way?
我能想到的一种方法是使用split()
并最终合并返回的最后两个字符串。有没有更好的办法?
采纳答案by Avinash Raj
Just pass the count as second parameter to str.split
function.
只需将计数作为第二个参数传递给str.split
函数。
>>> s = "238 NEO Sports"
>>> s.split(" ", 1)
['238', 'NEO Sports']
回答by wim
RTFM: str.split(sep=None, maxsplit=-1)
RTFM: str.split(sep=None, maxsplit=-1)
>>> "238 NEO Sports".split(None, 1)
['238', 'NEO Sports']
回答by Haresh Shyara
Use string.split()
使用 string.split()
string = "238 NEO Sports"
print string.split(' ', 1)
Output:
输出:
['238', 'NEO Sports']