How to turn a 'string list' into a real list?

后端 未结 4 1544
花落未央
花落未央 2021-01-25 19:42

I am opening a .txt file and have to use a list inside of it for a function I am writing. This is one of the lists given in the text file:

\'[24, 72         


        
4条回答
  •  遇见更好的自我
    2021-01-25 20:40

    You can use ast.literal_eval:

    In [8]: strs='[24, 72, 95, 100, 59, 80, 87]\n'
    
    In [9]: from ast import literal_eval
    
    In [10]: literal_eval(strs)
    Out[10]: [24, 72, 95, 100, 59, 80, 87]
    

    help on ast.literal_eval:

    In [11]: literal_eval?
    Type:       function
    String Form:
    File:       /usr/lib/python2.7/ast.py
    Definition: literal_eval(node_or_string)
    Docstring:
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
    Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
    and None.
    

提交回复
热议问题