All courses › Programming with Python › f-strings and formatting

f-strings and formatting

An f-string, written f"...", inserts values directly into text using curly braces. After a colon you can give a format spec, such as .2f for two decimals. This keeps printed output tidy and readable.

f"{x}"f"\{x\}"inserts the value of xx
f"{x:.2f}"f"\{x:.2f\}"xx with 2 decimals

Symbols

xxthe value being inserted

Example

x = 3.14159

f"{x:.2f}" gives "3.14".

.2f rounds to two decimals, it does not just truncate them.
Practise python basics for free →

← Lists · for loop and range →

Part of Programming with Python: Python basics.