Python: convert string to/from lists


/ Published in: Python
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.