Here is how to

choose the best string formatting: % vs. .format vs. f-string literal in Python.


In Python, there are multiple ways to format strings: the % operator, the .format() method, and f-string literals (introduced in Python 3.6). Let's explore each of these methods:

1. The % operator: The % operator allows you to format strings using placeholders. You use the % operator to specify the format and provide values in a tuple or dictionary. Example:

name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age)) 

Output

 


Explanation

2- The .format() method: The .format() method provides a more flexible way to format strings. It uses curly braces {} as placeholders and allows for positional or keyword arguments.

Example:

name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

3. The f-string literals: f-string literals are a more recent addition to Python (introduced in Python 3.6). They offer a concise and readable way to format strings by prefixing the string with an 'f' character and using curly braces {} to enclose expressions.

Example:

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

All three methods are valid and have their own advantages. f-string literals are generally preferred for their simplicity, readability, and ability to include expressions directly within the string.

However, the choice of string formatting method depends on personal preference and the specific requirements of your project or codebase.

Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.