Python: printing joined strings

The tutor brings up a couple of quick points about printing strings in Python.

In computer science, concatenate is another way of saying join. In Python, it’s done with the “plus” sign:

s0=”Hello.”
s1=” How are you?”
print(s0+s1)

gives the output

Hello. How are you?

However, when printing a string joined to a number, the number needs to be converted to a string:

val0=7*8
message=”Seven times eight equals ”
print(message+val0) #will produce an error

Changing val0 to a string like so

str(val0)

will correct the problem:

val0=7*8
message=”Seven times eight equals ”
print(message+str(val0)) #will work:)

produces the output

Seven times eight equals 56

HTH:)

Source:

Donaldson, Toby. Python, 3rd edition. Peachpit Press, 2014.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply