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

后端 未结 4 1493
花落未央
花落未央 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:31

    An answer has already been accepted, but I just wanted to add this for the record. The json module is really good for this kind of thing:

    import json
    s = '[24, 72, 95, 100, 59, 80, 87]\n'
    lst = json.loads(s)
    
    0 讨论(0)
  • 2021-01-25 20:38

    Use ast.literal_eval:

    strs='[24, 72, 95, 100, 59, 80, 87]\n'
    list_of_strs = ast.literal_eval(strs)
    

    Further help, leave a comment....

    0 讨论(0)
  • 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:<function literal_eval at 0xb6eaf6bc>
    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.
    
    0 讨论(0)
  • 2021-01-25 20:41

    you don't need to go importing anything for this

    s = '[24, 72, 95, 100, 59, 80, 87]'

    s.translate(None, '[]').split(', ') will give you a list of numbers that are strings

    if you want a list of ints try

    [int(i) for i in s.translate(None, '[]').split(', ')]

    0 讨论(0)
提交回复
热议问题