tags:

views:

88

answers:

5

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 would 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!

+2  A: 

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(',')]
Jweede
-1 for a few reasons1) don't use `str` as a variable name2) this wouldn't work because the result of the first `split` is a list
Daniel DiPaolo
yep. corrected in the edits.
Jweede
Don't use `list` as a variable name either.
Daniel DiPaolo
Another obvious mistake. Now corrected in the edit.
Jweede
Thanks for the feedback all (and removing the downvote). I'll remember to test before I post next time. :P
Jweede
+10  A: 
>>> s = "user1:type1,user2:type2,user3:type3"
>>> [tuple(x.split(':')) for x in s.split(',')]
[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]
FogleBird
perfect, thanks!
Lawrence
Remember to accept the answer! (Tick it.)
Xavier Ho
+3  A: 

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(",")]
Claudiu
+3  A: 
>>> s = "user1:type1,user2:type2,user3:type3"
>>> l = [tuple(user.split(":")) for user in s.split(",")]
>>> l
[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]
>>>

:)

Felix
+3  A: 

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

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