Python f-strings (formatted string literals) provide an elegant and efficient way to format strings in your Python programs.
Introduced in Python 3.6, f-strings make string interpolation easier, more readable, and faster than older Python methods like %
formatting and .format()
.
Basic Syntax
F-strings are defined by prefixing a string with f
or F
, allowing variables and expressions to be embedded directly within curly braces {}
, which serve as placeholders.
Take a look at the syntax, it's quite simple and very intuitive:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Explanation: This f-string directly injects the name
and age
variables into the string, producing a well-formatted output.
Output:
My name is Alice and I am 25 years old.
Using Expressions in F-Strings
You can include expressions inside f-strings, making them highly versatile. You just need to use your placeholders to include your expressions in the same way you would with a variable:
x = 5
y = 3
print(f"The sum of {x} and {y} is {x + y}.")
Explanation: The expression {x + y}
is evaluated within the string, dynamically inserting the result.
Output:
The sum of 5 and 3 is 8.
Formatting Numbers
One of the trickier aspects of using f-strings is formatting numbers, but thankfully you'll see that this is fairly straightforward.
1. Rounding Decimals
pi = 3.14159
print(f"Pi rounded to 2 decimal places: {pi:.2f}")
Explanation: The :.2f
format specifier ensures that the number is rounded to two decimal places.
Output:
Pi rounded to 2 decimal places: 3.14
2. Displaying Large Numbers with Commas
salary = 1000000
print(f"Annual salary: ${salary:,}")
Explanation: The :,
format specifier automatically inserts commas into large numbers for better readability.
Output:
Annual salary: $1,000,000
3. Displaying Percentages
progress = 0.85
print(f"Task completion: {progress:.0%}")
Explanation: The :.0%
format converts the decimal value into a percentage format without decimal places.
Output:
Task completion: 85%
Working with Dates and Time
You can format dates and times directly inside f-strings:
from datetime import datetime
today = datetime.now()
print(f"Today's date: {today:%Y-%m-%d}")
Explanation: The %Y-%m-%d
format string extracts and formats the year, month, and day from the datetime object.
Output:
Today's date: 2023-07-15 # Example output, depends on the current date
Multiline F-Strings
Use triple quotes for multi-line f-strings:
name = "Alice"
age = 25
bio = f"""
Name: {name}
Age: {age}
Status: Active
"""
print(bio)
Explanation: Triple quotes allow f-strings to span multiple lines while keeping them easy to read and format.
Output:
Name: Alice
Age: 25
Status: Active
Using F-Strings with Dictionaries
Access dictionary values directly in f-strings:
person = {"name": "Alice", "age": 25}
print(f"{person['name']} is {person['age']} years old.")
Explanation: Dictionary keys can be accessed inside f-strings just like normal variables.
Output:
Alice is 25 years old.
Key Takeaways
-
F-strings are prefixed with
f
and allow direct embedding of variables and expressions. -
They provide improved readability and performance compared to
.format()
and%
formatting. -
You can format numbers, dates, and multiline strings efficiently with f-strings in all of your Python projects.
Practice Exercise
Here's a simple challenge, try writing a Python script that asks for a user's name and age, then prints a greeting using f-strings:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello, {name}! You are {age} years old.")
Wrapping Up
Python f-strings simplify string formatting while improving readability and efficiency. Whether you're handling numbers, dates, or dictionaries, f-strings are the modern go-to solution for Python developers. Happy coding!