What Are Format Strings?

Format strings are strings that include placeholders that can be replaced with variable values and expressions at runtime. This makes it easy to create dynamic text output that embeds values or expressions within a string, instead of manually combining text and variables.

Why Use Format Strings?

Using format strings improves:

  • Readability - text and values appear together clearly

  • Maintainability - easier to update messages

  • Flexibility - supports data of different types and expressions
    Python supports multiple ways to format strings, but the most common and modern approach is formatted string literals (f-strings). Older approaches like .format() are still useful and widely supported.

1. Formatted String Literals (f-Strings)

Introduced in Python 3.6, f-strings are the preferred way to format strings because they are concise and readable. An f-string starts with the letter f before the opening quote, and expressions inside {} are evaluated at runtime and inserted into the string. ([turn0search0][turn0search3])

Example:

Python
name = "Alice" age = 25 print(f"Name: {name}, Age: {age}") # Output: # Name: Alice, Age: 25


You can also embed expressions and calculations inside {}:

Python
x = 10 y = 5 print(f"Sum: {x + y}") # Output: # Sum: 15

2. The format() Method

The format() method is a flexible approach that works in all Python 3 versions. You include placeholders {} in the string and call .format() with values to inject into those placeholders. 

Example:

Python
name = "Bob" age = 30 print("Name: {}, Age: {}".format(name, age)) # Output: # Name: Bob, Age: 30

You can also use named placeholders:

Python
print("City: {city}, Country: {country}".format(city="Berlin", country="Germany")) # Output: # City: Berlin, Country: Germany

3. Old-Style % Formatting

Python also supports older style formatting using the % operator (printf-style), though it is less common in modern code. For example:

Python
name = "Eve" print("Hello, %s" % name) # Output: # Hello, Eve

This syntax uses %s as a placeholder for strings.