开发者

split a string into a list of tuples

If i have a string like:

"user1:type1,user2:type2,user3:type3" 

and I want to convert this to a list of tuples like so:

[('user1','type1'),('user2','type2'),('user3','type3')]

how w开发者_StackOverflowould i go about doing this? I'm fairly new to python but couldn't find a good example in the documentation to do this.

Thanks!


>>> s = "user1:type1,user2:type2,user3:type3"
>>> [tuple(x.split(':')) for x in s.split(',')]
[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]


The cleanest way is two splits with a list comprehension:

str = "user1:type1,user2:type2,user3:type3"
res = [tuple(x.split(":")) for x in str.split(",")]


>>> s = "user1:type1,user2:type2,user3:type3"
>>> l = [tuple(user.split(":")) for user in s.split(",")]
>>> l
[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]
>>>

:)


If you want to do it without for loops, you can use map and lambda:

map(lambda x: tuple(x.split(":")), yourString.split(","))


Use the split function twice.

Try this for an example:

 s = "user1:type1,user2:type2,user3:type3"
 print [i.split(':') for i in s.split(',')]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜