In Python, string formatting is a crucial aspect of working with text and data representation. While the .format()
method has been a staple for a long time, the introduction of f-strings in Python 3.6 revolutionized the way we format strings. In this post, we’ll explore the power and flexibility of f-strings, highlighting their advantages over the legacy .format()
method. You may be surprised at just how much f-strings are capable of!
Interpolation is the technical term for the kind of substitution performed by f-strings in Python. Basically we create a placeholder in our output which gets dynamically filled in with the value of the expression provided.
Legacy Method: .format()
Before diving into f-strings, let’s briefly touch upon the traditional string formatting approach using the .format() method. Here’s a quick example:
name = "John"
age = 30
height = 6.2
formatted_string = "Name: {}, Age: {}, Height: {}".format(name, age, height)
print(formatted_string)
Output:
Name: John, Age: 30, Height: 6.2
F-strings: The Modern Solution
F-strings, short for “formatted string literals,” provide a concise and expressive way to embed expressions inside string literals. Let’s explore various scenarios and examples to illustrate their versatility.
Basic Examples
name = "John"
age = 30
# Basic f-string
formatted_string = f"Name: {name}, Age: {age}"
print(formatted_string)
Output:
Name: John, Age: 30
Recommended Python Books for Beginners
As an Amazon Associate I earn from qualifying purchases.
Expressions and Arithmetic
a = 5
b = 3
# Expressions inside f-string
result = f"The sum of {a} and {b} is {a + b}"
print(result)
Output:
The sum of 5 and 3 is 8
Padding and Alignment
num = 42
# Right-aligned with 5 spaces
formatted_num = f"Number: {num:5}"
print(formatted_num)
# Left-aligned with 8 spaces
formatted_num_left = f"Number: {num:<8}"
print(formatted_num_left)
Output:
Number: 42
Number: 42
Number of Digits for Float Display
pi = 3.141592653589793
# Display pi with 2 decimal places
formatted_pi = f"Pi: {pi:.2f}"
print(formatted_pi)
Output:
Pi: 3.14
Different Data Types
value = 42
percentage = 0.75
is_valid = True
# Handling different data types
formatted_data = f"Value: {value}, Percentage: {percentage}, Valid: {is_valid}"
print(formatted_data)
Output:
Value: 42, Percentage: 0.75, Valid: True
Dictionary Access
person = {'name': 'Alice', 'age': 25}
# Accessing dictionary values
formatted_dict = f"Name: {person['name']}, Age: {person['age']}"
print(formatted_dict)
Output:
Name: Alice, Age: 25
Inline Function Calls
def double(x):
return x * 2
number = 7
# Inline function call
formatted_result = f"Double of {number} is {double(number)}"
print(formatted_result)
Output:
Double of 7 is 14
Conclusion
F-strings bring clarity, conciseness, and enhanced functionality to string formatting in Python. With their expressive syntax and diverse capabilities, they have become the preferred choice for many developers. Whether you’re a beginner or an experienced Pythonista, incorporating f-strings into your coding arsenal is a step towards more readable and efficient code.