Python String Formatting

Python String Formatting

To make sure a string will display as expected, we can format the result with the format() method or using f-strings (available in Python 3.6+).

F-strings are the modern, recommended way to format strings in Python due to their readability and performance.


1. F-Strings (Formatted String Literals)

To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as placeholders for variables and other operations.

F-String Example

name = "John"
age = 36
txt = f"My name is {name}, I am {age}"
print(txt)

F-strings can also evaluate Python expressions directly inside the curly brackets!

F-String Expressions

price = 59
tax = 0.25
txt = f"The total price is {price + (price * tax)} dollars"
print(txt)

2. The format() Method

The format() method is an older but still very common way to format strings. It takes the passed arguments, formats them, and places them in the string where the placeholders {} are.

format() Method

quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))