-
Python-howto: converting a string into a tuple
Posted on October 6th, 2009 5 commentsRecently I had the problem to convert a string with coma-separated values into a tuple. Unlike a list a tuple is an immutable way to represent data, once it is created its values cannot be changed. Googling just brought up some really weird solutions which I either didn’t like or they did not work anyway. So I played around a little bit and came around with a single line solution that should work sufficiently.
Lets assume you have a string with coma-separated values like ‘value1, value2, value3′ and you want to convert it into a tuple (value1, value2, value3). A direct conversion from string to tuple is not possible, however there is a convenient way to create a list from a string using the .split() function. Lists can be easily converted into tuples. And this is basically the solution: convert the string into a list and then into a tuple. Putting it all together into a single line of code we end up with
s = 'bla, blub, blubber'
t = tuple(s.split(', '))
print t
# ('bla', 'blub', 'blubber')Please note that the argument for the split-method is a comma and a blank. The blank has to be added as the blanks in the string are considered as valid characters. If you just use a comma as an argument, the blanks will be part of the resulting tuples (ie. ‘ blub’ instead of ‘blub’).
So the conversion is not such a big mystery



