String Format
The Python Variables chapter showed that a string and a number can't simply be added together:
f-strings and the format() method can both mix text and numbers, though!
Example
Prompt
Demonstrate Python string format.
Output: complete Python program
main.py
age = 36
#This will produce an error:
txt = "My name is John, I am " + age
print(txt)
F-Strings
Python 3.6 brought in the f-string, which has since become the favoured tool for formatting text.
Making one is easy: write an f directly before the string literal, then use curly brackets {} to mark where variables and other operations should go.
Example
Prompt
Demonstrate Python f-strings.
Output: complete Python program
main.py
age = 36
txt = f"My name is John, I am {age}"
print(txt)
Placeholders and Modifiers
Inside a placeholder you can put a variable, an operation, a function, or a modifier that controls how the value is formatted.
Example
Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program
main.py
price = 59
txt = f"The price is {price} dollars"
print(txt)
Example
Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program
main.py
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Example
Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program
main.py
txt = f"The price is {20 * 59} dollars"
print(txt)
Example
Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program
main.py
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Example
Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program
main.py
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Example
Prompt
Demonstrate Python placeholders and modifiers.
Output: complete Python program
main.py
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))