Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

python - Syntax error on an f-string with nested quotation

code:

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)

get following errors:

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

Is that caused by the nested single/double quotations?

update: when I change to

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

I get another error:

NameError: name 'table' is not defined

what's the cause of this one?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It might be the nested quotations, in which case you should just replace the double-quotes at the beginning and ending with ''' - this is still a valid string literal in Python.

The other issue is that your f-string depends on variables not yet declared. In this problem, you would perhaps like to encapsulate this in a function that takes table and metric and returns the formatted string.

Consider this implementation -

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...