Convert string to list. Python [string.split() acting weird]

前端 未结 2 544
迷失自我
迷失自我 2020-11-29 11:28
temp = \"[\'a\',\'b\',\'c\']\"
print type(temp)
#string

output = [\'a\',\'b\',\'c\']
print type(output)
#list

so i have this temporary string whic

相关标签:
2条回答
  • 2020-11-29 11:47

    Use ast.literal_eval():

    Safely evaluate an expression node or a Unicode or Latin-1 encoded 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.

    >>> from ast import literal_eval
    >>> temp = "['a','b','c']"
    >>> l = literal_eval(temp)
    >>> l
    ['a', 'b', 'c']
    >>> type(l)
    <type 'list'>
    
    0 讨论(0)
  • 2020-11-29 12:01

    You can use eval:

    >>> temp = "['a', 'b', 'c']"
    >>> temp_list = eval(temp)
    >>> temp_list
    ['a', 'b', 'c']
    >>> temp_list[1]
    b
    
    0 讨论(0)
提交回复
热议问题