【问题标题】:Invalid syntax - Expression returning a string in f-String无效的语法 - 表达式返回 f-String 中的字符串
【发布时间】:2019-05-05 16:26:07
【问题描述】:

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

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

我在这里错过了什么?

【问题讨论】:

标签: python string python-3.x f-string


【解决方案1】:

您仍然必须遵守有关 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:

反斜杠不得出现在表达式中的任何位置。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      引号导致错误。

      使用这个:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-12
        • 2018-01-29
        • 2019-10-29
        • 2020-05-07
        • 1970-01-01
        • 2020-11-01
        • 2022-01-18
        • 2017-05-12
        相关资源
        最近更新 更多