ValueError:在python中进行字符串格式化时,字段名中出现意外的“{”

2024-10-01 07:17:17 发布

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

我正在尝试运行以下查询

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)

但是我越来越 ValueError:字段名中出现意外的“{” 我的设备id是{AB14233Q-2E60} 我错过了什么? 我真的很感激你能提供的任何帮助


Tags: andfromidformatdevicetableresultwhere
3条回答

您必须转义设备id中的引号

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

format方法将每个{}作为写入占位符的尝试

如果不是这样,你必须像这样逃离它们{{}}

因此,您可以将代码重写为:

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) 

你需要一个转义序列来解决这个问题。尝试添加双大括号,如{{ }}

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

希望这能起到作用

相关问题 更多 >