为什么此字符串不能与ast.literal_eval一起使用 [英] Why does this string not work with ast.literal_eval
本文介绍了为什么此字符串不能与ast.literal_eval一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到了格式错误的字符串错误.
I get a malformed string error.
这是我的测试
>>> eval("'Hello:: '+'fdsfds'")
'Hello:: fdsfds'
>>> import ast
>>> ast.literal_eval("'Hello:: '+'fdsfds'")
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
ast.literal_eval("'Hello:: '+'fdsfds'")
File "C:\Python27\lib\ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "C:\Python27\lib\ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
推荐答案
来自ast.literal_eval
docs :
提供的字符串或节点只能由以下Python文字结构组成:字符串,数字,元组,列表,字典,布尔值和无.
The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
使用+
的串联不包括在其中:它不是文字表达式,而是对str.__add__
的调用.与1+1
或"hello".upper()
无法正常工作的原因相同.
Concatenation using +
isn't included within that: it's not a literal expression, it's a call to str.__add__
. It's the same reason 1+1
or "hello".upper()
wouldn't work.
这篇关于为什么此字符串不能与ast.literal_eval一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文