NAS_2339
NAS_2339

Reputation: 353

ValueError: unexpected '{' in field name when doing string formatting in python

I'm trying to run the following query.

i=['qwerty12345']
%python
  query='''select 
column1,column2
from table
where hit_id='{hit_id}'
and device_id='{'{AB14233Q-2E60}'}'
'''.format(hit_id=i)
result= sqlContext.sql(query)

But I'm getting ValueError: unexpected '{' in field name my device_id is '{AB14233Q-2E60}' What am I missing here? I really appreciate any help you can provide.

Upvotes: 1

Views: 3701

Answers (4)

Yvonne Aburrow
Yvonne Aburrow

Reputation: 2728

Just in case this helps anyone else: one of my format placeholders accidentally had an incorrectly closed bracket, so check that your brackets are symmetrical.

Incorrect: {item1} {item2} {item3)

------------------------------------^

Correct: {item1} {item2} {item3}

Upvotes: 2

amichow
amichow

Reputation: 45

You would need an escape sequence to solve this. Try adding double curly braces like this {{ }} :

query= '''select 
    column1,column2
    from table
    where hit_id='{hit_id}'
    and device_id='{{'{{AB14233Q-2E60}}'}}'
    '''.format(hit_id=i)

This should hopefully do the trick

Upvotes: 0

Nerveless_child
Nerveless_child

Reputation: 1408

The format method takes every { and } as an attempt to write a placeholder.

When that is not the case, you have to escape them like this {{, }}.

So, you would rewrite your code to this:

i=['qwerty12345']
%python
query='''select 
column1,column2
from table
where hit_id='{hit_id}'
and device_id='{{'{{AB14233Q-2E60}}'}}'
'''.format(hit_id=i)
result= sqlContext.sql(query) 

Upvotes: 1

AlexisG
AlexisG

Reputation: 2484

You have to escape the quotes in your device_id

'''select 
column1,column2
from table
where hit_id='{hit_id}'
and device_id='{\'{AB14233Q-2E60}\'}'
'''

Upvotes: 0

Related Questions