TypeError using Concatenation in Python

Python is so good of handling types, that we are sometimes taken off guard when it doesn’t automatically do what we want. This is the case when we try to concatenate a string to print, but can happen whenever we concatenate non string types into a string, without first converting them.

Python using Laptop

Consider the following code

myInteger = 3
myString = "Woolly Hats"

# Just Print
print(myInteger)
print(myString)

#concatenate then print
print(myInteger + myString)

When we run this, we get an error

> python3 bad_printing.py
3
Woolly Hats
['blue', 'green', 'white']
[1, 2, 3]
Traceback (most recent call last):
  File "/myFiles/errors/bad_printing.py", line 13, in <module>
    print(myInteger + myString)
          ~~~~~~~~~~^~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'int' and 'str'

There are many ways to solve this, including using the fancier formatting. Often the simplest thing though, is one of the following

myInteger = 3
myString = "Woolly Hats"

# Just Print
print(myInteger)
print(myString)

# Fancier Printing
print(str(myInteger) + myString)
print(myInteger,myString)

Which we can see is successful. Note the first one isn’t formatted well, but a ‘ + ” ” +’ would fix it up nicely.

> python3 bad_printing.py
3
Woolly Hats
3Woolly Hats
3 Woolly Hats