Menu

Casting

The str() Function

Casting with str() turns a value into a string of text. You put the value inside the brackets, and str() hands back a new text version of it that you can use straight away.

This matters because the + operator does two different jobs depending on data type. Given two strings it joins them together; given two numbers it adds them. Given one string and one number it can do neither, so the program stops with an error. Casting with str() makes both operands text, so + joins them and a number can appear inside a message.

Worked example: a school's locker booking program stores the number of free lockers in an integer variable called lockers, but it needs that count inside a sentence. Writing str(lockers) where the count is needed gives text such as "24", which + can attach to the rest of the message. The cast happens only where it is written, so lockers is still an integer and you can carry on adding and subtracting with it.

badge = "Visitor"
lockers = 24
print(badge + " can use " + str(lockers) + " lockers.")

Output:

Visitor can use 24 lockers.

str() accepts any value you give it, so a real number such as 2.5 becomes the text "2.5", keeping the decimal point as a character.

ExpressionWhat happens
"Free lockers: " + "24"Two strings, so they are joined: Free lockers: 24
"Free lockers: " + 24A string and a number, so the program stops with an error
"Free lockers: " + str(24)The number is cast first, then joined: Free lockers: 24
crew = "Ground staff"
gates = 6
print("Gates opened by " + crew + ": " + gates)

Output:

TypeError: can only concatenate str (not "int") to str (line 3)

Practise this