【问题标题】:Syntax error on an f-string with nested quotation带有嵌套引号的 f 字符串的语法错误
【发布时间】:2021-02-01 22:55:37
【问题描述】:

代码:

schema = [{"name": "fb_table_1", "dimension": "department", "metrics": ["headcount"]},
          {"name": "fb_table_2", "dimension": "area", "metrics": ["sale"]},
          {"name": "fb_table_3", "dimension": "product", "metrics": ["quantity", "revenue"]}]

template = f"select date, '{table["dimension"]}', {table['dimension']}, '{metric}', {metric} from {table['name']}"
sql_2 = " union ".join([template for table in schema for metric in table["metrics"]])
print(sql_2)

得到以下错误:

template = f"select date, '{table["dimension"]}', {table['dimension']}, '{metric}', {metric} from {table['name']}"
                                               ^
SyntaxError: invalid syntax

是嵌套的单双引号引起的吗?

更新:当我更改为

template = f"select date, '{table['dimension']}', {table['dimension']}, '{metric}', {metric} from {table['name']}"

我收到另一个错误:

NameError: name 'table' is not defined

这是什么原因?

【问题讨论】:

  • 是的,你只需要转义f"select date, \"{table['dimension']}\"...

标签: python python-3.x string


【解决方案1】:

可能是嵌套的引号,在这种情况下,您应该只替换开头和结尾的双引号 ''' - 这在 Python 中仍然是有效的字符串文字。

另一个问题是你的 f-string 依赖于尚未声明的变量。在这个问题中,您可能希望将其封装在一个接受tablemetric 并返回格式化字符串的函数中。

考虑这个实现 -

schema = [{"name": "fb_table_1", "dimension": "department", "metrics": ["headcount"]},
          {"name": "fb_table_2", "dimension": "area", "metrics": ["sale"]},
          {"name": "fb_table_3", "dimension": "product", "metrics": ["quantity", "revenue"]}]

def get_required_string(table, metric):
    template = f'''
    select date, '{table["dimension"]}', {table['dimension']}, '{metric}', {metric} from {table['name']}
    '''
    return template

sql_2 = " union ".join([get_required_string(table, metric) for table in schema for metric in table["metrics"]])
print(sql_2)

【讨论】:

    【解决方案2】:

    是的,这是因为双引号:

    改成:

    template = f"select date, '{table['dimension']}', {table['dimension']}, '{metric}', {metric} from {table['name']}"
    

    【讨论】:

      猜你喜欢
      • 2022-11-21
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 2017-05-04
      • 2019-07-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-06
      相关资源
      最近更新 更多