语法无效 - 表达式返回 f-String 中的字符串

Invalid syntax - Expression returning a string in f-String

我喜欢 python 3.6 中的新 f-String,但在尝试 return 表达式中的字符串时遇到了几个问题。 以下代码不起作用并告诉我我使用了无效的语法,即使表达式本身是正确的。

print(f'{v1} is {'greater' if v1 > v2 else 'less'} than {v2}') # Boo error

它告诉我 'greater''less' 是意外标记。如果我将它们替换为包含字符串的两个变量,甚至是两个整数,错误就会消失。

print(f'{v1} is {10 if v1 > v2 else 5} than {v2}') # Yay no error

我在这里错过了什么?

只是混合引号,检查howto Formatted string literals

print(f'{v1} is {"greater" if v1 > v2 else "less"} than {v2}')

引号导致错误。

使用这个:

print(f'{v1} is {"greater" if v1 > v2 else "less"} than {v2}') 

您仍然必须遵守有关 quotes within quotes 的规则:

v1 = 5
v2 = 6

print(f'{v1} is {"greater" if v1 > v2 else "less"} than {v2}')

# 5 is less than 6

或者可能更具可读性:

print(f"{v1} is {'greater' if v1 > v2 else 'less'} than {v2}")

请注意,常规字符串允许 \',即对引号内的引号使用反斜杠。这在 f 字符串中是不允许的,as noted in PEP498:

Backslashes may not appear anywhere within expressions.