在带有条件的 f 字符串中打印变量

printing variables in an f-string with conditions

似乎无法打印带有条件的 f 字符串中的变量。我 运行 这个在烧瓶上,因此闪光灯。尝试删除大括号并将引号从单引号换成双引号,但仍然不起作用。输出应该是变量的值,而不是文字变量名 ex。 50 而不是 {driving_num}。

flash(f"{'The mandatory penalty for driving at {driving_num} km/h in a {speed_num} km/h zone is {msg[1]}' if msg[0] else 'The discretional penalty for driving at {driving_speed} km/h in a {speed_limit}km/h zone'} points.", WARNING_MSG)

您的内弦也需要 f-strings。忽略缩进只是为了更好的可读性:

flash(
    f"{
        f'The mandatory penalty for driving at {driving_num} km/h in a {speed_num} km/h zone is {msg[1]}'
        if msg[0] else
        f'The discretional penalty for driving at {driving_speed} km/h in a {speed_limit}km/h zone'
    } points.",
    WARNING_MSG
)