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:

Output (based on the current date and time):

Spacing/Alignment:

Output:

Datetime

Output:

Numbers

Output:

Other

Output:

Last updated