Python
String Formatting
Programming
Coding Tips
f-string literal

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

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

String formatting in Python refers to the process of inserting variables into strings. This technique is crucial for creating dynamic and easy-to-update messages or outputs in your programs. Python supports several methods for string formatting, each with its advantages and particular syntax. This article discusses the three primary methods: the old-style % formatting, the str.format() method, and the newer f-string literal introduced in Python 3.6.

1. Percent (%) Formatting

Percent formatting, also known as printf-style formatting, is borrowed from the C programming language. It uses % symbols as placeholders which get replaced by the values of variables.

Syntax:

python
name = "John"
age = 30
print("Hello, %s. You are %d years old." % (name, age))

Here, %s is used for strings, and %d is for integers. The variables to insert are provided as a tuple following the % operator.

Pros:

  • Familiar to those who have experience with C or similar syntax.
  • Concise for simple formatting tasks.

Cons:

  • It can become complicated and less readable with multiple parameters.
  • Less flexible compared to other techniques, lacking some advanced formatting features.

2. The str.format() Method

Introduced in Python 2.6, str.format() is more powerful than % formatting. It uses curly braces {} as placeholders.

Syntax:

python
name = "John"
age = 30
print("Hello, {}. You are {} years old.".format(name, age))

You can also include indices within the curly braces to specify the order:

python
print("Hello, {1}. You are {0} years old.".format(age, name))

Pros:

  • More flexible, supporting positional and keyword arguments.
  • More readable with named placeholders.

Cons:

  • Slightly more verbose than % formatting.
  • The syntax might feel more cumbersome for simple tasks.

3. f-String Literal (Formatted String Literals)

f-strings were introduced with Python 3.6 to simplify string formatting. They have a concise syntax, using f before the string and curly braces containing expressions that will be replaced directly.

Syntax:

python
name = "John"
age = 30
print(f"Hello, {name}. You are {age} years old.")

Their speed and readability make f-strings a popular choice for Python programmers.

Pros:

  • Concise and easy to read.
  • Fastest among the string formatting methods.
  • Expressions inside curly braces can be Python expressions.

Cons:

  • Only available in Python 3.6 and later.
  • Care must be taken not to introduce errors by embedding complex expressions.

Comparing the Methods

Here's a quick comparison in a table format:

Feature% Formatting.format()f-string
Python Version2.x, 3.x2.6+, 3.x3.6+
ReadabilityLowMediumHigh
FlexibilityLowHighHigh
SpeedModerateModerateFast
Inline expressionNoNoYes
Named PlaceholdersNoYesYes

Conclusion

While % formatting and the str.format() method still have their uses, f-strings provide a modern, readable, and performant way of formatting strings in Python. Choosing the right method depends on your Python version, specific needs, and personal preference for syntax. However, when using Python 3.6 and later, f-strings are generally recommended for most situations due to their ease of use and performance.


Course illustration
Course illustration

All Rights Reserved.