f-string Python

Introduction

f-strings were introduced in Python 3.6 and are described in PEP 498

Syntax

f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '

Example

value = 1 print(f'The value is {value}.') # Formatting value = 1234 print(f'input={value:#06x}') import datetime date = datetime.date(1991, 10, 12) print(f'{date} was on a {date:%A}') # Escaping with \ is not allowed print(f"{'quoted string'}")

python f-string.py

The value is 1. input=0x04d2 1991-10-12 was on a Saturday quoted string

!r

With !r you can output repr()

# !r a = "AAA" print(f"{a}") print(f"{a!r}")

python f-string.py

AAA 'AAA'

Article author: Andrei Olegovich

Banner image