Hone

Lessons · Python · turning a value into text

Turning a value into text

str(x) gives the text form of any value, so a number can sit inside a sentence.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Every message a program prints or writes to a file is text. The total is a number until you say str(total); then it can join a sentence, a filename, a label.

How to think about it

Ask: do I need this as text now? str() when you are about to print, join or display; keep it a number for as long as you are still doing maths.

Worked example

n = 42
A number.
s = str(n)
'42': two characters, no maths possible on it now.
print("Order " + s)
Order 42. Without str() the + would raise: text plus number is an error.
print(len(s))
2: the length of the text, not the size of the number.

Your turn

Put the count into a message.

msg = "Items: " + (count)

The trap

str(3.0) is '3.0', not '3'. The text keeps the float's decimal, so format numbers on purpose when they are for people.

Next in Python

Every Python lesson on one page

Practise turning a value into text on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.