It’s called Formatted String Literals.
Before this fancy new thing came along, you had to use the old-school string formatting methods like f-strings or str.format(). But now, with just a little prefix and some curly braces, you can embed Python expressions right into your strings!
Here’s an example:
# Define variables for name and age
name = "John"
age = 30
# Use f-string to format string with embedded Python expressions
print(f"My name is {name} and I am {age} years old.")
See how easy that was? No more messing around with format() or %-formatting. Just write your string like you normally would, but add an f at the beginning to indicate it’s a formatted string literal. Then, use curly braces to embed Python expressions inside the string.
You can also include format specifiers after the expression in the curly braces. For example:
# Define a variable "price" and assign it a value of 9.99
price = 9.99
# Use a formatted string literal to print a string with the value of "price" inserted
# The ".2f" format specifier ensures that the value of "price" is displayed with 2 decimal places
print(f"The price is {price:.2f}.")
This will round the price to two decimal places and display it like this: “The price is $9.99.”
So, what’s so great about formatted string literals? Well, for starters, they make your code more readable and concise. You don’t have to write out long format() strings or messy %-formatting syntax. Plus, you can embed Python expressions directly into the string, which is super handy when working with variables or calculations.
But that’s not all! Formatted string literals also support existing format string syntax from str.format(). So if you need more advanced formatting options, like padding or alignment, you can still use them in your f-strings.
In fact, here’s an example using both embedded expressions and format specifiers:
# Define variables for name and age
name = "John"
age = 30
# Use f-string to print a formatted string with embedded expressions and format specifiers
print(f"My name is {name} and I am {age:>5d} years old.")
# The f-string allows for embedding expressions within the string using curly braces
# The format specifier '>5d' aligns the age value to the right with a width of 5 characters
# This ensures that the output is neatly formatted with proper spacing and alignment
This will display the output like this: “My name is John and I am 30 years old.” (Note the padding with spaces.)
Formatted string literals are a powerful new feature in Python that make your code more readable, concise, and flexible. Give them a try and see how they can simplify your life as a programmer!