Ben Chuanlong Du's Blog

It is never too late to learn.

Format a String in Python

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.

In [3]:
"{x}".format(y=2)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-82a676436a84> in <module>
----> 1 '{x}'.format(y=2)

KeyError: 'x'
In [2]:
"{x}".format(x=1, y=2)
Out[2]:
'1'

f-string

  1. f-string is the most convenient way to format strings. However, be aware about the potential risk from injection attacks.

  2. f-string supports specifying a format for the result of the expression.

  3. f-string can be nested, which is really cool!

  4. 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 use chr(10) (which returns the backslash) instead.

  5. 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.

In [2]:
x = 1
f"{x:0>3}"
Out[2]:
'001'

f-strings can be nested.

In [3]:
x = 1
y = 3
f"{x:0>{y}}"
Out[3]:
'001'

The Old-style Formatting Operator %

It is not suggested to use % to format strings unless you have convincing reasons.

Formating Numbers

In [1]:
"{:3}".format(2)
Out[1]:
'  2'
In [2]:
"{:0>3}".format(2)
Out[2]:
'002'
In [ ]:
 

Comments