Last updated: Apr 9, 2024
Reading timeยท4 min
Use the str()
class to convert an object to a string.
The str()
class returns the string version of the given object.
my_int = 42 # โ Convert an object to a string result = str(my_int) print(result) # ๐๏ธ '42' print(type(result)) # ๐๏ธ <class 'str'> print(isinstance(result, str)) # ๐๏ธ True
The first example uses the str()
class to convert an object to a string.
The str() class takes an object and returns the string version of the object.
my_obj = 3.14 result = str(my_obj) print(result) # ๐๏ธ '3.14' print(type(result)) # ๐๏ธ <class 'str'>
If you need to convert a class object to a string, implement the __str__() method.
Use the __str__()
method to convert an object to a string.
The __str__()
method is called by str(object)
and the built-in format()
and print() functions and returns the
informal string representation of the object.
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return f'Name: {self.name}' bobby = Employee('bobbyhadz', 100) print(bobby) # ๐๏ธ Name: bobbyhadz
We defined the __str__()
method on the class to convert it to a string.
The __str__
method is called by str(object)
and the built-in format()
and
print()
functions and returns the informal string representation of the
object.
print()
function returns the output of the class's __str__()
method.__str__()
methodMake sure to return a string from the __str__()
method, otherwise a
TypeError
is raised.
For example, if we want to return the employee's salary from the __str__()
method, we have to use the str()
class to convert the value to a string.
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return str(self.salary) bobby = Employee('bobbyhadz', 100) print(bobby) # ๐๏ธ 100
The __str__()
method is called if you use the object in a formatted string
literal or with the str.format()
method.
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return str(self.salary) bobby = Employee('bobbyhadz', 100) result = f'Current salary: {bobby}' print(result) # ๐๏ธ Current salary: 100
The __str__()
method should return a string that is a human-readable
representation of the object.
If you need to convert a class instance to a JSON string, use the __dict__
attribute on the instance.
import json class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __str__(self): return str(self.salary) bobby = Employee('bobbyhadz', 100) json_str = json.dumps(bobby.__dict__) print(json_str) # ๐๏ธ '{"name": "bobbyhadz", "salary": 100}'
We used the __dict__
attribute to get a dictionary of the object's attributes
and values and converted the dictionary to JSON.
The json.dumps() method converts a Python object to a JSON formatted string.
__repr__()
There is also a __repr__()
method that can be used in a similar way to the
__str__()
method.
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def __repr__(self): return self.name bobby = Employee('bobbyhadz', 100) print(bobby) # ๐๏ธ 'bobbyhadz'
The
__repr__
method is called by the
repr() function and is
usually used to get a string that can be used to rebuild the object using the
eval()
function.
__str__()
method defined, but has __repr__()
defined, the output of __repr__()
is used instead.__str__()
and __repr__()
A good way to illustrate the difference between __str__()
and __repr__()
is
to use the datetime.now()
method.
import datetime # ๐๏ธ using __str__() print(datetime.datetime.now()) # ๐๏ธ 2022-09-08 14:29:05.719749 # ๐๏ธ using __repr__() # ๐๏ธ datetime.datetime(2022, 9, 8, 14, 29, 5, 719769) print(repr(datetime.datetime.now())) result = eval('datetime.datetime(2023, 2, 21, 13, 51, 26, 827523)') print(result) # ๐๏ธ 2023-02-21 13:51:26.827523
When we used the print()
function, the __str__()
method in the datetime
class got called and returned a human-readable representation of the date and
time.
repr()
function, the __repr__()
method of the class got called and returned a string that can be used to recreate the same state of the object.We passed the string to the eval()
function and created a datetime
object
with the same state.
Note that implementing the __repr__()
method in this way is not always
necessary or possible.
Having the __str__()
method return a human-readable string is sufficient most
of the time.
You can learn more about the related topics by checking out the following tutorials: