Python
String Formatting
f-strings
Programming Tips
Python 3

String formatting vs. .format vs. f-string literal

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Python, string formatting is an essential skill for creating dynamic and customized string outputs. Over the years, Python has evolved to offer multiple options for string formatting, each with its own syntactic style and features. Let's delve into the three most common methods: the % operator, the .format() method, and the f-string literal.

The % Operator

The % operator is one of the oldest methods of string formatting in Python. It's similar to the printf style in C, leveraging format specifier symbols.

Usage

The % operator uses placeholders within the string, marked by %, followed by a type indicator like d, s, f, etc.:

python
name = "Alice"
age = 30
formatted_string = "Name: %s, Age: %d" % (name, age)

Advantages

  • Simplicity: For small and simple strings, it can be quick and readable.
  • Familiarity for C Programmers: Those with a background in C may find this syntax intuitive.

Limitations

  • Limited Features: It doesn't support some advanced formatting capabilities.
  • Readability for Complex Strings: With multiple placeholders and variables, the readability diminishes.
  • Deprecation Concerns: Though not yet deprecated, it's considered outdated in favor of newer methods.

The .format() Method

Introduced in Python 2.6, the .format() method offers more advanced and flexible string formatting.

Usage

This method utilizes curly braces {} as placeholders, which can be empty or contain a positional/index or keyword argument:

python
name = "Bob"
age = 25
formatted_string = "Name: {}, Age: {}".format(name, age)

For more control, you can use:

python
formatted_string = "Name: {n}, Age: {a}".format(n=name, a=age)

Advantages

  • Versatility: Supports complex formatting, including alignment, width, and type specifiers.
  • Named Arguments: Allows the use of named placeholders for improved clarity.
  • Reusability in Expressions: Placeholders can be reused multiple times within the same string.

Limitations

  • Complexity for Simple Tasks: May feel over-engineered for simple string formatting tasks.
  • Performance: Slightly slower than the other two methods due to its dynamic nature.

F-string Literals

Introduced in Python 3.6, f-strings or "formatted string literals" are recognized for their efficiency and readability.

Usage

F-strings are prefixed with f and allow embedded Python expressions inside {}:

python
name = "Charlie"
age = 20
formatted_string = f"Name: {name}, Age: {age}"

Advantages

  • Readability: The syntax closely resembles written language, enhancing readability.
  • Efficiency: Generally faster because expressions are evaluated at runtime.
  • Support for Expressions: Arithmetic operations and even function calls can be seamlessly included within the brackets.
python
width = 10
formatted_string = f"Width: {width * 2}"

Limitations

  • Python 3.6+ Only: F-strings are not available in earlier versions.
  • Literal Requirement: Variables or expressions must be written directly within the string.

Key Differences

To efficiently choose the appropriate method for your needs, consider the following distinctions:

MethodPython VersionKey FeaturesLimitations
% OperatorAll VersionsSimple, C-like syntaxOutdated, less flexible
.format()2.6+Versatile, supports indexingMore verbose, slightly slower
F-string3.6+Readable, supports expressionsLimited to Python 3.6+

Conclusion

The choice between %, .format(), and f-strings largely depends on personal or project-specific priorities regarding readability, performance, and version compatibility. For entirely new projects especially with Python 3.6+, f-strings are often the recommended approach due to their clarity and performance advantages. However, it's beneficial to be familiar with all three to understand legacy code or when dealing with specific formatting requirements.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.