Converting a string of tuples to a list of tuples in Python

前端 未结 3 680
不思量自难忘°
不思量自难忘° 2020-12-11 22:14

How can I convert \"[(5, 2), (1,3), (4,5)]\" into a list of tuples [(5, 2), (1,3), (4,5)]

I am using planetlab shell that doe

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 22:57

    If ast.literal_eval is unavailable, you can use the (unsafe!) eval:

    >>> s = "[(5, 2), (1,3), (4,5)]"
    >>> eval(s)
    [(5, 2), (1, 3), (4, 5)]
    

    However, you should really overthink your serialization format. If you're transferring data between Python applications and need the distinction between tuples and lists, use pickle. Otherwise, use JSON.

提交回复
热议问题