If you create a variable, you can easily convert it to a string using the print function.
a = 5 print(a)
The variable is an integer, that is converted to string with the print function. Therefore you don’t have to convert it to a string before printing.
If you join variable with text, then you have to convert this variable to string before printing.
Otherwise, the interpreter will return the following error:
TypeError: can only concatenate str (not "int") to str
The correct code:
a = 5 print('John is ' + str(a) + ' years old.')
Run this code. The interpreter will return the following string:
John is 5 years old.
Inside the print function, there is another function, called str. It tries to convert everything to string. Now, there is no problem in merging this variable with other strings inside the print function.
Convert a class object to a string
Converting simple objects, like integers or floats is easy, but if you try to convert more complex objects, such as human-generated classes, the result may be different from what you expect.
Let’s try the following class:
class Person: name = "" age = 0 def __init__(self, person_name, person_age): self.name = person_name self.age = person_age p = Person('Tom', 34) print(p)
This class takes two arguments, and the constructor assigns them to the object variables when the object is created.
It’s fine, but when you try to run this code, you will get this result:
<__main__.Person object at 0x0000029C57B442E8>
You are going to get an object name and its memory address.
To change the default behavior of the string function, you have to overload the str function.
After modification, we have the following code:
class Person: name = "" age = 0 def __init__(self, person_name, person_age): self.name = person_name self.age = person_age def __str__(self): return self.name + ' is ' + str(self.age) + ' years old.' p = Person('Tom', 34) print(p)
After you run this code, the string message is going to be different than the last time.
Tom is 34 years old.