the*_*ish 2 python string python-3.x f-string
我喜欢 python 3.6 中的新 f-Strings,但是在尝试在表达式中返回 String 时我看到了一些问题。下面的代码不起作用并告诉我我使用了无效的语法,即使表达式本身是正确的。
print(f'{v1} is {'greater' if v1 > v2 else 'less'} than {v2}') # Boo error
Run Code Online (Sandbox Code Playgroud)
它告诉我,'greater'并且'less'是意料之外的标记。如果我用两个包含字符串的变量甚至两个整数替换它们,错误就会消失。
print(f'{v1} is {10 if v1 > v2 else 5} than {v2}') # Yay no error
Run Code Online (Sandbox Code Playgroud)
我在这里缺少什么?
您仍然必须遵守有关引号内引号的规则:
v1 = 5
v2 = 6
print(f'{v1} is {"greater" if v1 > v2 else "less"} than {v2}')
# 5 is less than 6
Run Code Online (Sandbox Code Playgroud)
或者可能更具可读性:
print(f"{v1} is {'greater' if v1 > v2 else 'less'} than {v2}")
Run Code Online (Sandbox Code Playgroud)
请注意,常规字符串允许\',即在引号内使用反斜杠作为引号。这在 f 字符串中是不允许的,如 PEP498 中所述:
反斜杠不能出现在表达式中的任何地方。