How to Format Strings in Python (f-strings & format)

Learn the best string formatting techniques in Python. Compare modern f-strings, format(), and percentage formatting with code examples.

Try Code in Editor

Explanation

Formatting strings is a daily necessity for rendering variables inside messages, outputting logs, printing console debugs, and building web pages. Python has evolved string formatting significantly over the years, offering multiple options to construct dynamic text representations safely and legibly.

In modern Python (3.6+), the standard and most popular approach is formatting with f-strings (Formatted String Literals). By prefixing a string with `f` or `F`, you can embed Python expressions or variables directly inside curly braces `{}`. These expressions are evaluated at runtime, making f-strings both faster and significantly more readable than older formatting methods.

Older Python code bases might utilize the `.format()` method or percent `%` formatting. While still supported, they are generally discouraged for new code. f-strings also support powerful inline format specifiers, enabling you to control decimal precision (e.g., `{value:.2f}`), align text, or format dates directly inside string variables.

Step-by-Step Implementation

  1. 1

    Prefix your string literal with the character f (e.g., f'Hello...').

  2. 2

    Insert variables or expressions directly inside curly braces {} within the string.

  3. 3

    Use format specifications like :.2f to handle decimal formatting inside the braces.

Code Example

This script demonstrates printing dynamic text blocks using f-strings, formatting floating-point floats, and using .format().

format_strings.py
Try in Editor
name = "Alice"
age = 30
pi = 3.14159

# 1. Using modern f-strings (Recommended)
greeting_f = f"Hello, my name is {name} and I am {age} years old."
print("f-string:", greeting_f)

# 2. formatting floats (2 decimal places precision)
precision_f = f"Pi rounded: {pi:.2f}"
print(precision_f)

# 3. Using the older .format() method
greeting_format = "Hello, my name is {} and I am {}.".format(name, age)
print(".format():", greeting_format)
Terminal Output
f-string: Hello, my name is Alice and I am 30 years old.
Pi rounded: 3.14
.format(): Hello, my name is Alice and I am 30.

Frequently Asked Questions

Are f-strings faster than .format() and % formatting?

Yes, f-strings are evaluated at runtime as optimized bytecode operations, making them faster than both .format() and % operators.

Can I run functions or evaluate expressions inside f-strings?

Yes, any valid Python expression (including mathematical operations, function calls, and dictionary lookups) can be evaluated inside the braces.

Related How-To Guides

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.