str.format¶
An exception will be thrown if the value for a key in the string is not specified, which means that you must specify values for all keys. However, it is OK if you specify values for keys that do not exist in the string. That is you can specify values for more keys than needed.
"{x}".format(y=2)
"{x}".format(x=1, y=2)
f-string¶
f-string is the most convenient way to format strings. However, be aware about the potential risk from injection attacks.
f-string supports specifying a format for the result of the expression.
f-string can be nested, which is really cool!
Backslash (
\
) cannot be used in a f-string. There are multiple ways to resolve this issue. First, you can precompute things needed to avoid using\
in a f-string. Second, you can usechr(10)
(which returns the backslash) instead.Be careful about security holes in f-String. Since f-String can run any code passed to it, it is open to injection attack. Avoid using f-String when user input involved.
Apply formatting (to the result of a expression) in f-string.
x = 1
f"{x:0>3}"
f-strings can be nested.
x = 1
y = 3
f"{x:0>{y}}"
The Old-style Formatting Operator %¶
It is not suggested to use %
to format strings unless you have convincing reasons.
Formating Numbers¶
"{:3}".format(2)
"{:0>3}".format(2)