Appearance
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:
- The % operator:
String formatting using the % operator
python
# 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."
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
- The
.format()method:
String formatting using the format method
python
# 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."- F-string literals (Python 3.6 and above):
String formatting using the f-string literals
python
# 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.