- Python convert any object to string
- # Table of Contents
- # Convert an Object to a String in Python
- # Convert a Class object to a String in Python
- # Make sure to return a String from the __str__() method
- # Converting a Class instance to a JSON string
- # Convert a Class object to a String using __repr__()
- # The difference between __str__() and __repr__()
- # Additional Resources
- How to change any data type into a string?
- 10 Answers 10
- object to string in Python
Python convert any object to string
Last updated: Feb 21, 2023
Reading time · 4 min
# Table of Contents
# Convert an Object to a String in Python
Use the str() class to convert an object to a string.
The str() class returns the string version of the given object.
Copied!my_int = 42 # ✅ Convert an object to a string result = str(my_int) print(result) # 👉️ '42' print(type(result)) # 👉️ 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.
Copied!my_obj = 3.14 result = str(my_obj) print(result) # 👉️ '3.14' print(type(result)) # 👉️
If you need to convert a class object to a string, implement the _ _ str _ _ () method.
# Convert a Class object to a String in Python
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.
Copied!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.
# Make sure to return a String from the __str__() method
Make 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.
Copied!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.
Copied!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.
# Converting a Class instance to a JSON string
If you need to convert a class instance to a JSON string, use the __dict__ attribute on the instance.
Copied!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) # 👉️ ''
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.
# Convert a Class object to a String using __repr__()
There is also a __repr__() method that can be used in a similar way to the __str__() method.
Copied!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.
If the class doesn’t have the __str__() method defined, but has __repr__() defined, the output of __repr__() is used instead.
# The difference between __str__() and __repr__()
A good way to illustrate the difference between __str__() and __repr__() is to use the datetime.now() method.
Copied!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.
When we used the 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.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How to change any data type into a string?
Do you want a human-readable string representation of the data? Or do you want a byte-oriented view of the memory containing the data?
10 Answers 10
myvariable = 4 mystring = str(myvariable) # '4'
also, alternatively try repr:
mystring = repr(myvariable) # '4'
This is called «conversion» in python, and is quite common.
I wouldn’t use repr(myvariable) — it often returns information about class type, memory address etc. It’s more useful for debugging. Use str(myvariable) for conversion to string and unicode(variable) for conversion to unicode.
str is meant to produce a string representation of the object’s data. If you’re writing your own class and you want str to work for you, add:
def __str__(self): return "Some descriptive string"
print str(myObj) will call myObj.__str__() .
repr is a similar method, which generally produces information on the class info. For most core library object, repr produces the class name (and sometime some class information) between angle brackets. repr will be used, for example, by just typing your object into your interactions pane, without using print or anything else.
You can define the behavior of repr for your own objects just like you can define the behavior of str :
def __repr__(self): return "Some descriptive string"
>>> myObj in your interactions pane, or repr(myObj) , will result in myObj.__repr__()
object to string in Python
I have some data objects on which I want to implement a to string and equals functions that go in depth. I implemented str and eq and although equality works fine I cannot make str behave in the same way:
class Bean(object): def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 def __str__(self): return str(self.__dict__) def __eq__(self, other): return self.__dict__ == other.__dict__
t1 = Bean("bean 1", [Bean("bean 1.1", "same"), Bean("bean 1.2", 42)]) t2 = Bean("bean 1", [Bean("bean 1.1", "same"), Bean("bean 1.2", 42)]) t3 = Bean("bean 1", [Bean("bean 1.1", "different"), Bean("bean 1.2", 42)]) print(t1) print(t2) print(t3) print(t1 == t2) print(t1 == t3)
, ], 'attr1': 'bean 1'> , ], 'attr1': 'bean 1'> , ], 'attr1': 'bean 1'> True False
since t1 and t2 contain the same values the equals return true (as expected) while since t3 contains a different value in the list the result is false (also as expected). What I would like is to have the same behavior for the to string (basically to also go in depth also for the elements in list (or set or dict . ). For print(t1) I would like to obtain something like:
Bean("bean 1", [Bean("bean 1.1", "same").__str__(), Bean("bean 1.2", 42).__str__()]).__str__
Since I do not know the types of the attributes attr1, attr2 in my Bean objects (they may be lists but also sets, dictionaries etc.) is would be nice to have a simple and elegant solution that would not require type checking . Is this possible ?