Python String Formatting
Python 3.6 gave us the f-string, which is now the favoured way to format text.
In earlier versions, the format() method filled that role.
F-Strings
An f-string lets you control how chosen parts of a string are formatted.
All it takes is an f written just before the string literal:
Example
A first, very simple f-string:
Output: complete Python program
txt = f"The price is 49 dollars"
print(txt)
Placeholders and Modifiers
Values get into an f-string through placeholders, written as {}. A placeholder can hold variables, operations and functions.
It can also carry a modifier, which decides how the value looks.
Write a modifier after a colon :, using a valid formatting type. For example, .2f asks for a fixed-point number showing 2 decimal places:
Example
Drop the price variable into a placeholder:
Output: complete Python program
price = 59
txt = f"The price is {price} dollars"
print(txt)
Example
Show the same price with 2 decimal places:
Output: complete Python program
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Placeholders and Modifiers
The value doesn't have to live in a variable. You can format it right in the placeholder:
Example
Format the number 95 with 2 decimal places:
Output: complete Python program
txt = f"The price is {95:.2f} dollars"
print(txt)
Perform Operations in F-Strings
Placeholders can also run Python operations. That covers plain math, math on variables, and even if...else statements, as the next three examples show:
Example
Multiply two numbers inside the placeholder and show the answer:
Output: complete Python program
txt = f"The price is {20 * 59} dollars"
print(txt)
Example
Work out the price with tax included, right in the placeholder:
Output: complete Python program
price = 59
tax = 0.25
txt = f"The price is {price + (price * tax)} dollars"
print(txt)
Example
Show "Expensive" when the price is above 50, and "Cheap" in any other case:
Output: complete Python program
price = 49
txt = f"It is very {'Expensive' if price>50 else 'Cheap'}"
print(txt)
Execute Functions in F-Strings
A placeholder can call functions as well. Python's built-in methods work, and so do functions you write yourself:
Example
Call the string method upper() to turn the value into capital letters:
Output: complete Python program
fruit = "apples"
txt = f"I love {fruit.upper()}"
print(txt)
Example
Write your own function that turns feet into meters, then call it in the placeholder:
Output: complete Python program
def myconverter(x):
return x * 0.3048
txt = f"The plane is flying at a {myconverter(30000)} meter altitude"
print(txt)
More Modifiers
Earlier in this lesson, the .2f modifier turned a number into a fixed-point value with 2 decimal places.
That is just one option, and other modifiers format values in different ways.
Example
Add a comma to separate the thousands:
Output: complete Python program
price = 59000
txt = f"The price is {price:,} dollars"
print(txt)
String format()
Before Python 3.6, formatting a string meant calling the format() method.
That method still works, although f-strings run faster and are the recommended choice.
The remaining examples on this page use format() so you can see how it works.
It also marks placeholders with curly brackets {}, but its syntax differs a little:
To control how a value is converted, add parameters between the curly brackets:
Example
Put a placeholder at the spot where the price should appear:
Output: complete Python program
price = 49
txt = "The price is {} dollars"
print(txt.format(price))
txt = "The price is {:.2f} dollars"
Multiple Values
Need more values? Pass them all to format():
Then give each one its own placeholder:
Example
Output: complete Python program
quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Index Numbers
A number inside the curly brackets, such as {0}, is an index. It guarantees that each value lands in the right placeholder:
It also lets you use one value several times, simply by repeating its index:
Example
Output: complete Python program
quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Example
Output: complete Python program
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
Named Indexes
Placeholders can have names as well. Write a name between the curly brackets, as in {carname}, and then supply the value under that same name when you call the method, as in txt.format(carname = "Ford"):
Example
Output: complete Python program
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))