• Python-howto: converting a string into a tuple

    Posted on October 6th, 2009 Nattl 5 comments

    Recently 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” RSS icon

    • 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

    • Ich schreib nicht nur für dich. Ich hoffe, du hattest ein Taschentuch oder zumindest ein Stamperl um das Hirn reinzufüllen :P

    • 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

    • Für mich hat’s aber eher nach einem trivialeren Problem geklungen, Sascha. :P

      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.)

    • Also was die 3er Version angeht, fürcht’ ich, hat Python das selbe Problem wie PHP. Es gibt einfach zu viele Libraries und Frameworks, die nur mit der alten Version rennen. PHP 5 ist 2004? rausgekommen und noch immer gibt es unheimlich viele Applikationen, die in PHP 4 gecoded sind (WordPress z.b.).

      Nichtsdestotrotz is Python eine mächtige Sprache, die du dir nicht entgehen lassen solltest.


    Leave a reply