我有一个变量,用于存储包含单引号和双引号的字符串。例如,一个变量test7是以下字符串:
{'address_components': [{'long_name': 'Fairhope', 'short_name': 'Fairhope' 'types': ['locality', 'political']}...
我需要将此变量传递给ast.literal_eval,然后传递给json.dumps,最后传递给json.loads。但是,当我尝试将其传递给ast.literal时,出现错误:
line 48, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
{'address_components': [{'long_name': 'Fairhope', 'short_name': 'Fairhope' 'types': ['locality', 'political']}...'
^
IndentationError: unexpected indent
如果我将字符串复制并粘贴到literal_eval中,则使用三引号将其有效:
#This works
ast.literal_eval('''{'address_components': [{'long_name': 'Fairhope', 'short_name': 'Fairhope' 'types': ['locality', 'political']}...''')
#This does not work
ast.literal_eval(testing7)
答案 0 :(得分:2)
错误似乎与引号无关。该错误的原因是字符串前面有空格。 例如:
>>>ast.literal_eval(" {'x':\"t\"}")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/leo/miniconda3/lib/python3.6/ast.py", line 48, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/home/leo/miniconda3/lib/python3.6/ast.py", line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
{'x':"t"}
^
IndentationError: unexpected indent
您可能需要先将字符串剥离,然后再将其传递给函数。此外,我在您的代码中没有看到双引号和单引号混合在一起。在单引号字符串中,您可能希望使用\来转义单引号。例如:
>>> x = ' {"x":\'x\'}'.strip()
>>> x
'{"x":\'x\'}'
>>> ast.literal_eval(x)
{'x': 'x'}