nbas
nbas

Reputation: 45

Passing a string variable to ast.literal_eval that has leading spaces

I have a variables that stores strings which contain both single and double quotes. For example, one variable, testing7, is the following string:

    {'address_components': [{'long_name': 'Fairhope', 'short_name': 'Fairhope' 'types': ['locality', 'political']}...

I need to pass this variable through ast.literal_eval and then json.dumps, and finally json.loads. However when I try to pass it through ast.literal I get an error:

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

If I copy and past the string into literal_eval it will work if enclosed with triple quotes:

#This works
ast.literal_eval('''{'address_components': [{'long_name': 'Fairhope', 'short_name': 'Fairhope' 'types': ['locality', 'political']}...''')

#This does not work
ast.literal_eval(testing7)

Upvotes: 3

Views: 5467

Answers (1)

lee
lee

Reputation: 96

It seems that the error isn't related to quotes. The cause of the error is that you have space in front of the string. For example:

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

You may want to strip the string before passing it into the function. Besides, I didn't see mixed double quotes and single quotes in your code. In a single quoted string, you may want to use \ to escape the single quote. For example:

>>> x = '    {"x":\'x\'}'.strip()
>>> x
'{"x":\'x\'}'
>>> ast.literal_eval(x)
{'x': 'x'}

Upvotes: 8

Related Questions