Saturday, March 14, 2026
HomeLanguagesConvert Object to String in Python

Convert Object to String in Python

Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting an object to a string.

Converting Object to String

Everything is an object in Python. So all the built-in objects can be converted to strings using the str() and repr() methods.

Example 1: Using str() method

Python3




# object of int
Int = 6
  
# object of float
Float = 6.0
  
# Converting to string
s1 = str(Int)
print(s1)
print(type(s1))
  
s2= str(Float)
print(s2)
print(type(s2))


Output:

6
<class 'str'>
6.0
<class 'str'>

Example 2: Use repr() to convert an object to a string

Python3




print(repr({"a": 1, "b": 2}))
print(repr([1, 2, 3]))
  
# Custom class
class C():
    def __repr__(self):
        return "This is class C"
  
# Converting custom object to 
# string
print(repr(C()))


Output:

{'a': 1, 'b': 2}
[1, 2, 3]
This is class C

Note: To know more about str() and repr() and the difference between to refer, str() vs repr() in Python

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32506 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6882 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12099 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7255 POSTS0 COMMENTS
Thapelo Manthata
6967 POSTS0 COMMENTS
Umr Jansen
6956 POSTS0 COMMENTS