Chapter 4: Sequence types

Formatting strings

face Josiah Wang

f-strings (formatted string literals) help make string formatting easier and more readable.

>>> name = "Josiah"
>>> count = 10
>>> possession = "cars"
>>> print(f"{name} has {count} {possession}")
???

You can also format floating point values.

>>> pi = 3.14159265359
>>> print(f"PI with three significant digits: {pi:.3}")
PI with three significant digits: 3.14
>>> print(f"PI with three decimal points: {pi:.3f}")
PI with three decimal points: 3.142
>>> print(f"PI with three significant digits, 9-character width is {pi:9.3}")
PI with three significant digits, 9-character width is      3.14
>>> print(f"PI with three significant digits, 9-character width padded with 0 is {pi:09.3}")
PI with three significant digits, 9-character width padded with 0 is 000003.14

And you can left/centre/right justify strings (giving a fixed length).

>>> title = "Title"
>>> print(f"| {title : <20} | {title : ^20} | {title : >20} |")
| Title                |        Title         |                Title |