Practice with F-Strings
Warmup Exercise
Write a program that prompts the user for two integers and displays their product. The output must match the example below (with user input as shown). Your solution may assign only two variables. You must use an f-string for the last line of output.
Enter a number: 2
Enter another number: 3
2 times 3 equals 6
What a Format Specifier Says
Every f-string follows the same plan: inside the braces, a colon separates what to print on the left from how to print it on the right. The part after the colon is the specifier, and the way to learn it is one example at a time.
Assume these four variables, then cover the Output column, predict each row, and check yourself in Thonny's Shell.
| f-string | Output |
|---|---|
f"{price}" |
4 |
f"{price:.2f}" |
4.00 |
f"${price:.2f}" |
$4.00 |
f"{total:.2f}" |
1234.57 |
f"{total:.0f}" |
1235 |
f"{total:,.2f}" |
1,234.57 |
f"{7/3:.3f}" |
2.333 |
f"{share:.1%}" |
87.4% |
f"{2**10:,}" |
1,024 |
f"[{price:5}]" |
[ 4] |
f"{price:02d}" |
04 |
f"[{name:>8}]" |
[ Sam] |
f"[{name:<8}]" |
[Sam ] |
f"[{name:^9}]" |
[ Sam ] |
f"{name[0]}{name[-1]}" |
Sm |
f"{price} items at ${total/price:.2f} each" |
4 items at $308.64 each |
The square brackets in four of those rows are not part of the formatting. They are there so you can see the spaces, which is the whole point of those four.
Six observations worth pulling out of that table, because they cover almost everything you will need this semester:
.2fmeans two digits after the decimal point, always, even when the number is a whole one. This is the specifier you will reach for most often, and4.00is why.- Changing the number changes the digits, so
.0fgives you no decimal point at all, and.3fgives you three. Notice that1234.5678became1235, which means these specifiers round rather than truncate. - A comma asks for thousands separators, and it goes before the dot, as in
,.2f. - A percent sign multiplies by 100 and adds the sign, so a
shareof0.8735displays as87.4%. You do not multiply by 100 yourself. - A bare number is a minimum width, which pads the value with spaces to fill it.
Add
>,<, or^to say whether the value hugs the right, hugs the left, or centers. Numbers pad on the left when you do not say, and strings pad on the right, so it is worth saying. Put a0in front of the width and it pads with zeros instead of spaces, which is how a clock gets04rather than4. - Anything can go on the left of the colon, not just a variable name: arithmetic, an index, a whole expression. The last two rows show that, and the final one puts several expressions and a specifier in a single string.
Write out five more f-strings of your own using these variables, predict each one, and check them. Then throw the table away and try to produce a given output from scratch, which is the direction a quiz asks in.
round() and .2f are not the same thing
round(price, 2) and f"{price:.2f}" both give you two decimal places, and they are not the same thing.
One changes the value and one changes only how the value is displayed, which is why only one of them can show you 1.50.
Work out which is which, and be able to say why in one sentence.
A few other places to look:
- Python documentation, Formatted String Literals, which is the short official introduction.
- Tech With Tim, "f-Strings in Python - String Formatting" (video).
- Real Python, "Python's F-String for String Interpolation and Formatting", which is thorough enough to be a reference rather than a read-through.
- Real Python, "Python Modulo Operator (%): How to Use Mod in Python", if
%is the operator that keeps not making sense.
Example Format Specifiers
"""Example format specifications using f-strings."""
number = int(input("Please enter an integer: "))
print()
print(f"In decimal (base 10), the number is {number:d}.")
print(f"In binary (base 2), the number is {number:b}.")
print(f"In hexadecimal (base 16), the number is {number:x}.")
print()
number = int(input("Integer between 0 and 99: "))
print()
print(f"Five chars wide, padded with spaces: {number:5d}")
print(f" padded with zeros: {number:05d}")
print()
number = int(input("Enter a 7+ digit integer: "))
print()
print(f"With comma separators: {number:,d}")
print()
number = float(input("Enter a floating-point number: "))
print()
print(f"In exponent notation, the number is {number:e}.")
print(f"In fixed-point notation, the number is {number:f}.")
print(f"Rounded to two decimal places: {number:.2f}")
print()
Practice Problems
Choose one of the problems below
- Solve the problem as a team
[15 min] - Present solution(s) to the class
[10 min] - If you finish early, solve the other problem
Average Speed Calculator
Write a program named bike_speed.py that asks the user for the length
of a bike race in miles and their finishing time for the race in hours,
minutes, and seconds. The program then outputs their average speed in
both miles per hour and kilometers per hour. When you output the speed
you should show exactly 2 digits past the decimal place.
1 mile = 1.60934 kilometers.
Here is an example run of the program:
How many miles did you race? 18.66
How much time did that take you in hours, minutes, and seconds?
Hours: 0
Minutes: 43
Seconds: 49
Your speed was 25.55 mph, which is 41.12 kph.
Hint 1: Figure out how to solve the problem by hand before you try to code anything. You can't program what you can't solve with a pen and paper.
Hint 2: You'll want to get your time into one unit. Dealing with 3 separate units is not good for computation. At the end of the day, we need to calculate distance / time in hours to solve the problem, so what is the total time in hours? Notice that 0 hours, 43 minutes, and 49 seconds is ~0.7303 hours. How do you calculate this total? With \(0+\frac{43}{60}+\frac{49}{3600}\). How can you do this for other numbers of hours, minutes, and seconds?
Miles, Furlongs, and Feet
Write a program called feet_convert.py that inputs a total number
of feet and divide that number into miles, furlongs, and feet.
(A furlong is some old English measure nobody uses anymore, but let's do it anyway!)
1 mile is 5280 feet, and 1 furlong is 660 feet.
Here is an example run of the program:
Enter a total number of feet: 12345
12345 total feet is 2 mile(s), 2 furlong(s), and 465 feet.
Hint 1: Figure out how to solve the problem yourself by hand on paper. You can't code something you don't know how to solve.
Hint 2: You will need to use floor division and remainder (// and %).
Hint 3: Create a variable for the remaining feet. In the example above, the remaining feet is initially 12345. Once you figure out there are two full miles in 12345 feet (2 full miles is 10560 feet), then the remaining feet is 1785. How many full furlongs are in 1785 feet? Well, 2 again, since \(660\times2 = 1320\). And finally after we remove those 1320 from 1785, the remaining feet is 465.