Python String Formatting: Three Practical Methods
String formating in Python allows you to insert variables in to strings in a controllled manner. This tutorial covers the three most common approaches.
Method 1: Using the % Operator
The % operator is the oldest way to format strings in Python. The %s placeholder represents a string, while %d represents an integer. The number of placeholders must match the number of variables provided.
>>> user = "Alice"
>>> score = 95
>>> print("Student: %s, Score: %d" % (user, score))
Student: Alice, Score: 95
Multiple placeholders require parentheses around the variables.
Method 2: Using the format() Function
The format() method offers more flexibility. It accepts an arbitrary number of arguments, and positional indexes can be used to control the order.
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0}".format("hello", "world")
'world hello'
>>> "{0} {1} {0}".format("hello", "world")
'hello world hello'
You can also use named parameters:
>>> print("Product: {name}, Price: {price}".format(name="Widget", price=29.99))
Product: Widget, Price: 29.99
Using dictionaries:
>>> data = {"item": "Laptop", "cost": 999}
>>> print("Item: {item}, Cost: {cost}".format(**data))
Item: Laptop, Cost: 999
Using lists with indices:
>>> inventory = ["Monitor", 199]
>>> print("Product: {0[0]}, Price: {0[1]}".format(inventory))
Product: Monitor, Price: 199
Using objects:
class Product:
def __init__(self, id):
self.id = id
item = Product(42)
print("Product ID: {0.id}".format(item))
Output:
Product ID: 42
Method 3: Using f-string
F-strings, introduced in Python 3.6, provide the most concise syntax. Prefix the string with f and embed variables directly within curly braces.
>>> name = "Bob"
>>> quantity = 5
>>> print(f"Item: {name}, Quantity: {quantity}")
Item: Bob, Quantity: 5
F-strings support expressions and function calls within the placeholders:
>>> price = 100
>>> tax = 0.08
>>> print(f"Total: {price + (price * tax):.2f}")
Total: 108.00