-
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
5 responses to “Python-howto: converting a string into a tuple”

-
Also ich hab das jetzt mehrmals gelesen……… mir wäre dabei fast das Hirn aus dem Ohr gesickert;-)
Tut mir leid mit deinem Wochenende dass ins Wasser fiel.
lg
Sascha -
Sascha October 8th, 2009 at 14:02
JAJA Nattl, sei du ruhig frech*g*
Vergiss aber net WER DEINEN WOHNUNGSSCHLÜSSEL HAT
Näheres in Kürze unter http://www.nattls-liebesnest.at
lg
Sascha -
Martin October 8th, 2009 at 16:10
Für mich hat’s aber eher nach einem trivialeren Problem geklungen, Sascha.
Tuples in der Form sind aber anscheinend auch etwas Python-spezifisches (wobei ich mich in Python fast nicht auskenne. Ich warte mal, bis sich die 3er-Version weit genug verbreitet hat.)
Leave a reply
-


Sascha October 7th, 2009 at 22:22