在python中使用分隔符拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4717074/
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
Splitting strings using a delimiter in python
提问by test
OK so I have a string that has this:
好的,所以我有一个字符串:
Dan|warrior|54
I'm trying to make so I can use python and split it using |as the delimiter. Here's what I have so far:
我正在尝试使我可以使用 python 并将其|用作分隔符进行拆分。这是我到目前为止所拥有的:
#!/usr/bin/env python
dan = 'dan|warrior|54'
print dan.split('|')
and that results into this:
结果如下:
['dan', 'warrior', '54']
I know it's incomplete but what do I have to do to finish it? Yes, I tried googling this problem... but it's not happening. :(
我知道它不完整,但我必须做什么才能完成它?是的,我尝试使用谷歌搜索这个问题......但它没有发生。:(
I want so that I can choose specifically which one from the delimiter so if I was dan.split('|')[1].. it would pick warrior. See my point?
我想要这样我就可以从分隔符中具体选择哪一个,所以如果我是dan.split('|')[1].. 它会选择warrior. 明白我的意思了吗?
采纳答案by Lennart Regebro
So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:
因此,您的输入是 'dan|warrior|54' 并且您想要“warrior”。你这样做:
>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

