python将一个字符串转为一个字典【面试题详解】

今天爱分享给大家带来python将一个字符串转为一个字典【面试题详解】,希望能够帮助到大家。
如何将字符串转成字典,不适用eval


s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"


从python2.6开始,你可以使用内建模块 ast.literal_eval


>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}


这个做法比直接eval更安全 帮助文档


>>> help(ast.literal_eval)
Help on function literal_eval in module ast:

literal_eval(node_or_string)
    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.


举例


>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "", line 1, in 
File "", line 1, in 
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
    onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
    names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "", line 1, in 
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
    return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
    raise ValueError('malformed string')
ValueError: malformed string


人已赞赏
Python

python字符串格式化 % vs format优缺点与区别【面试题详解】

2020-12-22 17:56:13

Python

python如何获取一个字符的ASCII码【面试题详解】

2020-12-22 18:00:17

'); })();