Howard Paget
Projects
About

Python String Interpolation

Feb 12, 2022

Python has a number of ways to do string interpolation: %-formatting, str.format, and the focus of this article f-strings. f-strings provide a concise and readable create formatted strings.

Simple Example

To use f-string interpolation add an ‘f’ to the beginning of the string and insert the variables in curly brackets.

name = 'Joe'
surname = 'Bloggs'

print(f'Hello {name} {surname}')
# Hello Joe Bloggs

Formatting Numbers

To format a number to N decimal places simply a :.Nf after the variable.

mass = 86.25

print(f'Mass: {mass:.1f}kg')
# Mass: 86.3kg

You can also perform calculating in the curly brackets.

print(f'Mass: {mass * 2.2:.1f}lb')
# Mass: 189.8lb

And call functions.

def weight(mass):
    return mass * 9.8

print(f'Weight: {weight(mass):.1f}N')
# Weight: 845.3N

Padding

To add padding to a number :0N or :N after the variable where N is the amount of padding. :0N pads with zeroes and :N pads with spaces.

id = 12

print(f'Id: {id:04}')
# Id: 0012

print(f'Id: {id:4}')
# Id:   12

Formatting Dates

To format a date add the format (the format you would pass to strftime()) e.g :%Y-%m-%d after the variable.

date_of_birth = dt.datetime(1997, 8, 25)

print(f'Date of Birth: {date_of_birth:%Y-%m-%d}')
# Date of Birth: 1997-08-25