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

In Python, there are several ways to format strings. Here is a brief overview of the three most common ways:

  1. The % operator:
# Formatting with the % operator
name = 'John'
age = 30
print('Hello, %s. You are %d years old.' % (name, age))

# Output: "Hello, John. You are 30 years old."

Watch a course Python - The Practical Guide

  1. The .format() method:
# Formatting with the .format() method
name = 'John'
age = 30
print('Hello, {}. You are {} years old.'.format(name, age))

# Output: "Hello, John. You are 30 years old."
  1. F-string literals (Python 3.6 and above):
# Formatting with f-string literals
name = 'John'
age = 30
print(f'Hello, {name}. You are {age} years old.')

# Output: "Hello, John. You are 30 years old."

Which method you choose will depend on your personal preference and the version of Python you are using. The % operator is an old method that is still supported in newer versions of Python, but it is generally considered less readable than the other two methods. The .format() method is more flexible and powerful than the % operator, and it is often the recommended way to format strings in Python. F-string literals are the most concise and easy-to-read way to format strings, but they are only available in Python 3.6 and above.