How to clean up string in to list of tuples of floats

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vvkonline
    New Member
    • May 2010
    • 2

    #1

    How to clean up string in to list of tuples of floats

    Hello I want to ask for some help here, I got this data as a string

    s = "[(0, 0.5, 0), (3.7, 5, 6), (5, 6, 7), (9, 9, 9), (12.607, 10, 2)]"

    but I would like to have it as it were actual list of tuples with floats.

    any tips would be great.
    Thank you
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    This kind of thing is one of the great strengths of python, and similar. The eval command is probably what you're after. Please note that this command needs to be used with caution - as spiderman's uncle said: "with great power, comes great responsibility! "

    Anyway, here's an interactive session:
    Code:
    In [1]: s = "[(0, 0.5, 0), (3.7, 5, 6), (5, 6, 7), (9, 9, 9), (12.607, 10, 2)]"
    In [2]: s2=eval(s)
    
    In [3]: s2
    Out[3]: 
    [(0, 0.5, 0),
     (3.7000000000000002, 5, 6),
     (5, 6, 7),
     (9, 9, 9),
     (12.606999999999999, 10, 2)]

    Comment

    • vvkonline
      New Member
      • May 2010
      • 2

      #3
      oh amazing : ) that's time saver i was starting to think I'll have to do all sort of striping, tokenizing , converting

      thanks a lot Glenton, i'm go read up on eval more. so i know better

      Comment

      Working...