Formatted strings

Formatted strings, also known as “f-strings,” are a way to include variables inside string literals, introduced in Python 3.6. They offer a more convenient and easier-to-read way to format strings, compared to the older .format() method or using the % operator.

name = "Alice"
print(f"Hello, {name}!")

In this example, {name} inside the f-string is replaced with the value of the name variable, which is “Alice”. The output of this code would be:

Hello, Alice!

F-strings support a variety of formatting options, such as adding commas as thousand separators, padding with zeros, and formatting dates. Here are some examples:

  • Commas as thousand separators:

value = 1000000
print(f"Value: {value:,}")

Output:

Value: 1,000,000

Underscore as thousand separators:

value = 1000000
print(f"Value: {value:_}")

Output:

Value: 1,000,000
  • Right padding with zeros:

value = 123
print(f"Value: {value:0>5}")
  • Date formatting:

import datetime
now = datetime.datetime.now()
print(f"Current date: {now:%Y-%m-%d %H:%M:%S}")

Output (based on the current date and time):

Current date: 2024-02-19 12:34:56

Spacing/Alignment:

var: str = 'var'
# Right alignment
# 17* space + var = 20
print(f"{var:>20}:")
# Left alignment
print(f"{var:<20}:")
# Center alignment
print(f"{var:^20}:")

# Fill empty spaces
print(f"{var:_>20}:")
print(f"{var:#<20}:")
print(f"{var:|^20}:")

Output:

                var:
var                :
         var       :
         
________________var:
var################:
|||||||||var|||||||:

Datetime

from datetime import datetime

now: datetime = datetime.now()
print(f"{now:%d.%m.%y (%H:%M:%S)}")
print(f"{now:%c}"
print(f"{now:%I%p}")

Output:

19.02.24 (09:05:51)
Mon Feb 19 09:05:51 2024
09AM

Numbers

n: float = 1234.5678
# Rounded
print(f"Result: {n:.2f}")
print(f"Result: {n:.0f}")

# Rounded with 1000 seperator
print(f"Result: {n:,.3f}")
print(f"REsult: {n:_.3f}")

Output:

Result: 1234.57
Result: 1235
Result: 1,234.568
Result: 1_234.568

Other

a: int = 5
b: int = 10
var: str = "Bob says hi"
 
print(f"{a + b =}")
print(f"{var =}")

Output:

a + b = 15
var = "Bob says hi"

Last updated