Exercises
String Formatting
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print each row as a name padded to 12 characters, then the age right-aligned in 4.
Python
rows = [("Ada", 36), ("Grace", 45)]
for name, age in rows:
# print the aligned row
passUse :<12 for the name and :>4 for the age.
rows = [("Ada", 36), ("Grace", 45)]
for name, age in rows:
print(f"{name:<12}{age:>4}")Exercise 2Passed
The template is a variable, so an f-string will not do. Fill it using format().
Python
template = "{} is {}"
# print Ada is 36
template.format(...) fills the empty braces in order.
template = "{} is {}"
print(template.format("Ada", 36))Exercise 3Passed
Print the number with thousands separators and two decimals.
Python
n = 1234.5678
# print 1,234.57
The spec is a comma followed by .2f.
n = 1234.5678
print(f"{n:,.2f}")