Convert string representation of list into list

前端 未结 1 1496
醉话见心
醉话见心 2021-01-24 11:49
list_string = \"[1,3,4,6]\"

I tried list_string[1:-1] but it is giving 1,3,4,6. I also tried list_string.split(\',\')

相关标签:
1条回答
  • 2021-01-24 12:22

    Assuming your string is a simple list/dict/combination of lists and dicts, you can use one of the two packages mentioned below, listed in order of preference.

    json

    >>> import json
    >>> json.loads('[1, 2, 3]')
    [1, 2, 3]
    

    This is definitely the preferred method if you are parsing raw json strings.


    ast.literal_eval

    >>> import ast
    >>> ast.literal_eval('[1, 2, 3]')
    [1, 2, 3]
    

    ast.literal_eval will safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None, bytes and sets.

    Also json.loads is significantly faster than ast.literal_eval. Use this ONLY IF you cannot use the json module first.


    yaml

    In some cases, you can also use the pyYAML library (you'll need to use PyPi to install it first).

    >>> import yaml
    >>> yaml.safe_load('[1, 2, 3]')
    [1, 3, 4, 6] 
    
    0 讨论(0)
提交回复
热议问题