Issue: mixing f-String with str.format
Your dict-value contains an f-String which is immediately evaluated.
So the expression inside the curly-braces (was {0}
) is directly interpolated (became 0
), hence the value assigned became "Hi There, 0"
.
When applying the .format
argument "Dave"
, this was neglected because string already lost the templating {}
inside. Finally string was printed as is:
Hi There, 0
Attempt to use f-String
What happens if we use a variable name like name
instead of the constant integer 0
?
Let's try on Python's console (REPL):
>>> d = {"message": f"Hi There, {name}"}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined
OK, we must define the variable before. Let's assume we did:
>>> name = "Dave"; d = {"message": f"Hi There, {name}"}
>>> print(d["message"])
Hi There, Dave
This works. But it requires the variable or expression inside the curly-braces to be valid at runtime, at location of definition: name
is required to be defined before.
Breaking a lance for str.format
There are reasons
- when you need to read templates from external sources (e.g. file or database)
- when not variables but placeholders are configured independently from your source
Then indexed-placeholders should be preferred to named-variables.
Consider a given database column message with value "Hello, {1}. You are {0}."
. It can be read and used independently from the implementation (programming-language, surrounding code).
For example
- in Java:
MessageFormat.format(message, 74, "Eric")
- in Python:
message.format(74, 'Eric')
.
See also:
Format a message using MessageFormat.format() in Java