为什么这个字符串不能与ast.literal一起使用_

2024-10-01 17:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到一个格式错误的字符串。

这是我的证词

>>> 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

Tags: inpyhelloconvertstringlibevalline
1条回答
网友
1楼 · 发布于 2024-10-01 17:25:50

ast.literal_evaldocs

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()不起作用的原因是一样的。

相关问题 更多 >

    热门问题