Python string type list converted to real type of list

We are in the process of writing code, often using the for loop, to the circulation list, so if we get a list of type str, and it carried out the for loop, the result of the following code and see:

str_list = str(['a','b','c'])

for row in str_list:
    print(row)

result:
Python string type list converted to real type of list

Then put the for loop str type of each character have a list of a print out of the loop, and this result is not what we want, then how to solve this problem? , Using the third-party modules, see following code

from ast import literal_eval

# 假设拿到了一个str类型的列表
str_list = str(['a','b','c'])

print(type(str_list)) # <class 'str'>

# 通过 literal_eval 这个函数,将str类型的列表转换成类型为list的真正的列表类型
new_list = literal_eval(str_list)

print(type(new_list)) # <class 'list'>

# 然后就可以通过for循环获取到列表中的每一个值
for row in new_list:
     print(row)

# 执行结果
'''
a
b
c
'''

Ast function literal content will determine the need to calculate the calculation is not a legal type of python, if it is then carried out operations, or not carry out operations

Guess you like

Origin blog.51cto.com/12643266/2424664