Rocket's status report is a tangle of commas and quote marks. One line has nine pieces glued together, and the temperature shows eleven digits after the decimal point.
"Nobody can read this," he admits. "Not even me."
Raven squints at the screen. "What do you notice?" she asks. "The message is mostly words. The values are just a few small holes in the sentence."
Nova draws a sentence in the air with three glowing gaps. "Would you like a hint?" she asks. "Python has a string that fills its own gaps. You put an f in front and the values in curly brackets."
Rocket rewrites the longest line, and the report suddenly looks like a real sentence.
An f-string has the letter f right before the opening quote. Inside it, anything in curly brackets { } is worked out and dropped into the text.
You can put a variable, or even a calculation, inside the brackets. Add :.1f after a number to show one digit after the decimal point, or :.2f for two.
# status.py
probe = "Probe 7"
battery = 87
temp = 21.456
print(f"{probe} battery: {battery}%")
print(f"Temperature: {temp:.1f} degrees")
print(f"Next check in {battery // 10} minutes") Probe 7 battery: 87% Temperature: 21.5 degrees Next check in 8 minutes
Without the f, Python would show the curly brackets and the names inside them as plain text. Forgetting the f is a very common slip.
Add a comma after the colon to put commas in big numbers, like {distance:,}. You can combine tricks too: {speed:,.1f} adds commas and keeps one decimal.
Remember that the work happens inside the curly brackets, so you can do math there.
# probe_report.py
probe = "Probe 9"
distance = 12500
speed = 3.14159
print(f"{probe} has gone {distance:,} km")
print(f"Speed: {speed:.2f} km per second")
print(f"Half way: {distance // 2:,} km") Probe 9 has gone 12,500 km Speed: 3.14 km per second Half way: 6,250 km
| Statement | True or false? |
|---|---|
| f"{5 + 5}" shows 10. | ? |
| "{5 + 5}" with no f shows 10. | ? |
| :.2f shows two digits after the decimal point. | ? |
| The f goes after the closing quote mark. | ? |
f-strings make your output clear and friendly. Tomorrow you will put everything together in a trip time calculator.