Step 3
Working with text
Join strings, call string methods and build readable messages with f-strings.
Strings
A string is text in quotes; "red" and 'red' are the same string. Join strings with +:
color = "red"
print(color + " ball") # red ball
+ only joins strings to strings: "x = " + 0.5 is an error. str(0.5) turns a number into the string "0.5".
Strings come with tools. len(color) is the number of characters, 3. Methods are tools attached to a value, called with a dot after it: color.upper() gives "RED", and color.title() gives "Red".
f-strings
Joining with + gets clumsy fast. An f-string has an f before the opening quote, and puts any value written in curly braces straight into the text:
x = 0.1234
print(f"The {color} ball is at x = {x} m")
# The red ball is at x = 0.1234 m
Add a format after a colon inside the braces to control how a number looks. :.2f means "2 digits after the decimal point":
print(f"x = {x:.2f} m") # x = 0.12 m
You'll use this all the time to print positions and sensor readings without a wall of digits.
Your task
The starter has a ball's color and its position x in metres.
- Set
shouttocolorin capital letters, using a string method. - Set
labelto text likered ball at x = 0.12 m, withxrounded to 2 decimal places. Use an f-string. - Print
label.