A Guide to Python's format() Method

A guide to the str.format() method for string formatting in Python. Learn how to use this powerful and flexible method with positional and keyword arguments to create dynamically formatted strings.

Before the introduction of f-strings in Python 3.6, the modern and most powerful way to format strings was using the str.format() method. While f-strings are now preferred for their readability and performance, str.format() is still extremely common in existing codebases and remains a versatile tool for string formatting.

str.format() was introduced in Python 2.6 as a more powerful and flexible alternative to the old C-style % formatting.

The Basic Syntax

The format() method works on a string and uses curly braces {} as placeholders. You then pass the values you want to insert into the placeholders as arguments to the method.

name = "Alice"
age = 30

# The placeholders {} are replaced by the arguments to format()
in order.
message = "My name is {} and I am {} years old.".format(name, age)

print(message)
# Output: My name is Alice and I am 30 years old.

Using Positional and Keyword Arguments

str.format() gives you a lot of control over how the placeholders are filled.

By Position:

You can refer to arguments by their position (index).

message = "{0} is {1} years old, and {0} works as a developer.".format(name, age)

print(message)
# Output: Alice is 30 years old, and Alice works as a developer.

By Keyword:

You can also use keyword arguments, which can make your formatting strings much more readable.

message = "My name is {user_name} and I am {user_age} years old.".format(user_name="Bob", user_age=25)

print(message)
# Output: My name is Bob and I am 25 years old.

This is often clearer because the placeholder name describes what is being inserted.

Formatting Options

Similar to f-strings, str.format() supports a rich mini-language for formatting the output. You add a colon : after the placeholder name to specify the format.

Formatting Numbers:

pi = 3.14159

# Format as a float with 2 decimal places
message = "The value of pi is approximately {:.2f}.".format(pi)

print(message)
# Output: The value of pi is approximately 3.14.

Padding and Alignment:

for i in range(1, 4):
    # Right-align and pad with zeros to a width of 3
    print("File number: {:0>3}".format(i))

Output:

File number: 001
File number: 002
File number: 003

str.format() vs. f-strings

So why are f-strings now preferred over str.format()?

  • Readability: With f-strings, the variable is right there inside the curly braces, which is generally easier to read than matching placeholders to arguments at the end of the line.

    • f"Hello, {name}" vs. "Hello, {}".format(name)
  • Performance: f-strings are evaluated at runtime and are generally faster than str.format().

However, there is one key situation where str.format() is still necessary: when your format string comes from a template or a source other than a string literal in your code.

# Imagine this template comes from a file or a database
email_template = "Hello, {name}. Welcome to our service!"

# You can't use an f-string here because 'name' is not defined yet.
# You must use .format()

message = email_template.format(name="Charlie")
print(message)

Conclusion

The str.format() method is a powerful and flexible tool for string formatting in Python. It was a huge improvement over the old % style and provides a rich set of options for controlling your output. While the more modern f-strings have replaced it for most day-to-day formatting tasks due to their superior readability and performance, str.format() remains an essential tool to know, especially when working with existing codebases or when dealing with format strings that are not known at compile time.