为什么 f-string 文字在这里不起作用,而 %()s 格式却起作用?
Why does f-string literal not work here, whereas %()s formatting does?
我正在尝试使用实际验证器中的 min/max 值来格式化我的验证器消息。
这是我的烧瓶表格:
class MyForm(FlaskForm):
example = IntegerField(label=('Integer 0-10'),
validators=[InputRequired(), NumberRange(min=0, max=10, message="must be between %(min)s and %(max)s!")])
使用 message="must be between %(min)s and %(max)s!"
给出了预期的输出:
must be between 0 and 10!
而使用 message=f"must be between {min} and {max}!"
给出了输出:
must be between <built-in function min> and <built-in function max>!
如何为我的验证程序消息使用 f 字符串格式?这与 运行 时的 f 字符串评估有关吗?我不完全理解它背后的概念,我只知道它是字符串格式的首选方式。
"must be between %(min)s and %(max)s!"
是一个字符串文字,Flask 稍后将对其执行搜索和替换,而 f"must be between {min} and {max}!"
是一种更简单、更有效的表达方式 "must be between " + str(min) + " and " + str(max) + "!"
。计算结果为您描述的字符串。
在传递给 IntegerField
.
之前,立即 评估 f 字符串文字
>>> foo = 3
>>> print(f'{foo}')
3
另一个字符串包含 literal %(...)
子字符串
稍后与 %
运算符一起使用。
>>> print("%(foo)s")
%(foo)s
>>> print("%(foo)s" % {'foo': 3})
3
你必须声明这样的变量,比如
min = 1
max = 2
print(f"must be between {min} and {max}!")
但请考虑使用稍微不同的变量名,以免隐藏内置函数。
好的,我现在明白了,您想将其用作一种字符串模板。
我正在尝试使用实际验证器中的 min/max 值来格式化我的验证器消息。
这是我的烧瓶表格:
class MyForm(FlaskForm):
example = IntegerField(label=('Integer 0-10'),
validators=[InputRequired(), NumberRange(min=0, max=10, message="must be between %(min)s and %(max)s!")])
使用 message="must be between %(min)s and %(max)s!"
给出了预期的输出:
must be between 0 and 10!
而使用 message=f"must be between {min} and {max}!"
给出了输出:
must be between <built-in function min> and <built-in function max>!
如何为我的验证程序消息使用 f 字符串格式?这与 运行 时的 f 字符串评估有关吗?我不完全理解它背后的概念,我只知道它是字符串格式的首选方式。
"must be between %(min)s and %(max)s!"
是一个字符串文字,Flask 稍后将对其执行搜索和替换,而 f"must be between {min} and {max}!"
是一种更简单、更有效的表达方式 "must be between " + str(min) + " and " + str(max) + "!"
。计算结果为您描述的字符串。
在传递给 IntegerField
.
>>> foo = 3
>>> print(f'{foo}')
3
另一个字符串包含 literal %(...)
子字符串
稍后与 %
运算符一起使用。
>>> print("%(foo)s")
%(foo)s
>>> print("%(foo)s" % {'foo': 3})
3
你必须声明这样的变量,比如
min = 1
max = 2
print(f"must be between {min} and {max}!")
但请考虑使用稍微不同的变量名,以免隐藏内置函数。
好的,我现在明白了,您想将其用作一种字符串模板。