Transform string list into tuple list

Asked

Viewed 1,909 times

6

I have this:

l=['Car 8', 'Bike 5', 'Train 10']

and I’d like to have something like this:

[('Car','8'), ('Bike','5'), ('Train','10')]

How could I turn a list of strings into something like a list of string tuples?

  • 1

    Jose, there is the possibility of there being white spaces in the text, something like 'Other Bike 5'?

1 answer

7


Using list comprehensions can do:

>>> [tuple(x.split(' ')) for x in l]
>>> [('Car', '8'), ('Bike', '5'), ('Train', '10')]

Every element is made split with space and on the result of split, which is a list, is built the tuple using tuple.

See the code running on Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.