F-Strings
Overview
Introduced in Python 3.6, Formatted String Literals (F-Strings) revolutionized string formatting. Before F-strings, developers used the clunky %s operator or the .format() method. F-strings allow you to embed variables and expressions directly inside string literals seamlessly by prefixing the string with f and wrapping variables in curly braces {}. Not only are they the most readable formatting option, but they are also executed at C-level speed, making them the fastest formatting method available.
Syntax
name = "Alice"
age = 25
score = 88.75
# The old, deprecated ways:
print("Name: " + name + ", Age: " + str(age))
print("Name: {}, Age: {}".format(name, age))
# The modern F-String way:
print(f"Name: {name}, Age: {age}")
# Executing math and rounding floats directly inside the braces
print(f"Next year, {name} will be {age + 1}.")
print(f"Rounded score: {score:.1f}") # Outputs 88.8Common Pitfalls
- Forgetting to place the
fprefix before the quotes. Writing"{name}"will literally print the text '{name}' instead of substituting the variable. - Using the exact same quote type inside the curly braces as the outer string.
f"{user["name"]}"will cause a SyntaxError. You must mix quotes:f"{user['name']}".
Interview Questions
f"{variable=}" do (introduced in Python 3.8)?It is an incredibly useful debugging feature. It prints both the variable's name and its value. E.g., if count = 10, print(f'{count=}') outputs count=10.
Real-World Example
Generating dynamic SQL queries (Note: beware of SQL injection, this is just for syntax illustration) or API endpoints.
base_url = "https://api.example.com"
user_id = 9921
resource = "orders"
# Constructing URLs dynamically is vastly easier with f-strings
endpoint = f"{base_url}/users/{user_id}/{resource}"
print(endpoint) # https://api.example.com/users/9921/ordersCheck Your Knowledge
Test your understanding of F-Strings with these quick questions.