Posted By

magicrebirth on 12/22/09


Tagged

list python String Eval


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

silang
gartenstuhl


Python: convert string to/from lists


 / Published in: Python
 

// Is there a way in python to convert a list say [1,2,3,4] to a string and // also how to convert a string to a list?

// use str() or repr() to convert to a string. // eval() will convert back to a list.

  1. x = range(10)
  2. print x
  3. # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  4. print str(x)
  5. # '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
  6. print repr(x)
  7. # '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
  8. y = str(x)
  9. z = eval(y)
  10. print x == z
  11. # 1
  12. print z
  13. # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Report this snippet  

You need to login to post a comment.