python如何将字符串形式的列表转成列表

Posted by 二田 on 2018-10-28

例子

json

1
2
3
4
5
6
7
>>> str='[1,2,3]'
>>> type(str)
<class 'str'>
>>> import json
>>> json.loads(str)
[1, 2, 3]
>>>

ast. literal_eval

1
2
3
4
5
6
>>> import ast
>>> str='[1,2,3]'
>>> type(str)
<class 'str'>
>>> ast.literal_eval(str)
[1, 2, 3]

eval

1
2
3
4
5
>>> str='[1,2,3]'
>>> type(str)
<class 'str'>
>>> eval(str)
[1, 2, 3]

不推荐,不信你看,就问你怕不怕

1
2
3
4
5
6
7
8
9
10
>>> str="__import__('os').system('df -h')"
>>> type(str)
<class 'str'>
>>> eval(str)
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk1s1 233Gi 156Gi 64Gi 71% 1672221 9223372036853103586 0% /
devfs 202Ki 202Ki 0Bi 100% 698 0 100% /dev
/dev/disk1s4 233Gi 13Gi 64Gi 18% 13 9223372036854775794 0% /private/var/vm
map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net
map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home