Python String Formatting with F-Strings
Discover the modern way to format strings in Python using F-Strings, introduced in Python 3.6. Learn how F-Strings simplify string formatting by placing an f
in front of the string literal. Compare this with the older format()
method used before Python 3.6.
Python String Formatting
F-Strings, introduced in Python 3.6, are now the preferred method for
formatting strings. Before Python 3.6, the format()
method
was used.
F-Strings
F-Strings allow you to format specific parts of a string by placing an
f
in front of the string literal:
Example
txt = f"The price is 49 dollars"
print(txt)
Output
The price is 49 dollars
Placeholders and Modifiers
F-Strings use placeholders ({}
) to include variables,
operations, functions, and modifiers within the string:
Example
price = 59
txt = f"The price is {price} dollars"
print(txt)
Output
The price is 59 dollars
Modifiers can format values by adding a colon (:
) followed
by a formatting type, like .2f
for fixed-point numbers with
two decimals:
Example
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Output
The price is 59.00 dollars
You can format values directly within the f-string:
Example
txt = f"The price is {95:.2f} dollars"
print(txt)
Output
The price is 95.00 dollars
Perform Operations in F-Strings
F-Strings allow you to perform operations inside placeholders, such as math operations:
Example
txt = f"The price is {20 * 59} dollars"
print(txt)
Output
The price is 1180 dollars
Or perform operations on variables:
Example
price = 59
tax = 0.25
txt = f"The price is {price + (price * tax)} dollars"
print(txt)
Output
The price is 73.75 dollars
You can also use if...else statements inside placeholders:
Example
price = 49
txt = f"It is very {'Expensive' if price > 50 else 'Cheap'}"
print(txt)
Output
It is very Cheap
Execute Functions in F-Strings
Functions can be executed inside placeholders:
Example
fruit = "apples"
txt = f"I love {fruit.upper()}"
print(txt)
Output
I love APPLES
You can also use user-defined functions:
Example
def myconverter(x):
return x * 0.3048
txt = f"The plane is flying at a {myconverter(30000)} meter altitude"
print(txt)
Output
The plane is flying at a 9144.0 meter altitude
More Modifiers
There are several other modifiers for formatting values, such as using a comma as a thousand separator:
Example
price = 59000
txt = f"The price is {price:,} dollars"
print(txt)
Output
The price is 59,000 dollars
Here is a list of all the formatting types:
Code | Description |
---|---|
:< |
Left aligns the result within the available space |
:> |
Right aligns the result within the available space |
:^ |
Center aligns the result within the available space |
:= |
Places the sign to the leftmost position |
:+ |
Uses a plus sign to indicate if the result is positive or negative |
:- |
Uses a minus sign for negative values only |
: |
Inserts an extra space before positive numbers and a minus sign before negative numbers |
:, |
Uses a comma as a thousand separator |
:_ |
Uses an underscore as a thousand separator |
:b |
Binary format |
:c |
Converts the value into the corresponding Unicode character |
:d |
Decimal format |
:e |
Scientific format, with a lowercase e |
:E |
Scientific format, with an uppercase E |
:f |
Fixed point number format |
:F |
Fixed point number format, in uppercase format (showing inf and nan as INF and NAN) |
:g |
General format |
:G |
General format (using an uppercase E for scientific notations) |
:o |
Octal format |
:x |
Hex format, lowercase |
:X |
Hex format, uppercase |
:n |
Number format |
:% |
Percentage format |
String format()
Before Python 3.6, the format()
method was used for string
formatting. It is still available but less preferred due to the
efficiency and readability of f-strings. The
format()
method also uses curly brackets as placeholders,
with slightly different syntax:
Example
price = 499
txt = "The price is {} dollars"
print(txt.format(price))
Output
The price is 499 dollars
You can add parameters inside the curly brackets to specify formatting:
Example
txt = "The price is {:.2f} dollars"
If you want to use multiple values, add more values to the
format()
method and placeholders:
Example
quantity = 30
itemno = 867
price = 99
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Output
I want 30 pieces of item number 867 for 99.00 dollars.
Using index numbers ensures values are placed correctly:
Example
quantity = 30
itemno = 895
price = 94
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Output
I want 30 pieces of item number 895 for 94.00 dollars.
You can refer to the same value more than once by using index numbers:
Example
age = 50
name = "Alan"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
Output
His name is Alan. Alan is 50 years old.
Named indexes can also be used by entering a name inside the curly brackets:
Example
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Tata", model = "Safari"))
Output
I have a Tata, it is a Safari.