1 min read

Python String Formatting

Python provides multiple ways to format strings. The most common methods are F-Strings, the format() method, and the % operator.

F-Strings (Formatted String Literals)

Introduced in Python 3.6, F-Strings are the recommended way to format strings because they are readable, concise, and faster.

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

You can also evaluate expressions inside the curly braces:

price = 59
txt = f"The price is {price * 1.20:.2f} dollars"
print(txt)

The format() Method

The format() method was introduced in Python 3.0. It allows you to format selected parts of a string.

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

You can use index numbers to ensure the arguments are placed in the correct placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

The % Operator (Old Style)

This is the old style of formatting, similar to printf in C. It is still supported but generally less preferred than F-Strings or format().

name = "John"
txt = "Hello, %s" % name
print(txt)

programming/python/python