Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

python - Why does f-string literal not work here, whereas %()s formatting does?

I am trying to format my validator message with the min/max values in the actual validator.

Here's my Flask Form:

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!")])

Using message="must be between %(min)s and %(max)s!" gives me the expected output:

must be between 0 and 10!

Whereas using message=f"must be between {min} and {max}!" gives me the output:

must be between <built-in function min> and <built-in function max>!

How can I use f-string formatting for my validator message? Is this something related to f-string evaluating at run-time? I don't fully understand the concept behind it, I just know it's the preferred way to string format.

question from:https://stackoverflow.com/questions/66051054/why-does-f-string-literal-not-work-here-whereas-s-formatting-does

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

"must be between %(min)s and %(max)s!" is a string literal that Flask will later perform a search-and-replace on, while f"must be between {min} and {max}!" is a simpler and more efficient way to say "must be between " + str(min) + " and " + str(max) + "!". That evaluates to the string you described.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...