Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string into list of tuples?

I have a string of key-value pairs, which unfortunately are separated by the same symbol. Is there a way to "just split" it into a list of tuples, without using a lambda?

Here is what i have:

Moscow|city|London|city|Royston Vasey|vilage

What i want:

[("Moscow","city"), ("London", "city")....] 
like image 737
Ibolit Avatar asked Mar 18 '13 15:03

Ibolit


People also ask

How do I turn a string into a list tuple?

When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.

Can we convert string to tuple in Python?

Method #1 : Using map() + int + split() + tuple() This method can be used to solve this particular task. In this, we just split each element of string and convert to list and then we convert the list to resultant tuple.


1 Answers

This is a pretty easy one really...

first, split the string on '|' then zip every other element together:

data = s.split('|')
print zip(data[::2],data[1::2])

In python3, you'll need: print(list(zip(data[::2],data[1::2]))

like image 77
mgilson Avatar answered Oct 15 '22 21:10

mgilson