How to change any data type into a String in Python?
Last Updated :
15 Jul, 2025
In Python, it's common to convert various data types into strings for display or logging purposes. In this article, we will discuss How to change any data type into a string.
Using str() Function
str() function is used to convert most Python data types into a human-readable string format. It is the most commonly used method when we want a string representation of an object for printing or displaying to users.
Python
a = 123
str_a = str(a)
print(str_a)
1. Converting Float to String
Python
b = 45.67
str_b = str(b)
print(str_b) # Output: "45.67"
2. Converting Boolean to String
Python
c = True
str_c = str(c)
print(str_c)
3. Converting List to String
Python
d = [1, 2, 3]
str_d = str(d)
print(str_d)
Other methods we can use to convert data types to strings are:
Using repr() Function
repr() function is used to convert an object into a string that is more formal or "developer-friendly." It is meant to provide a detailed, unambiguous string representation of the object that could often be used to recreate the object.
1. Converting Integer to String
Python
a = 123
repr_a = repr(a)
print(repr_a) # Output: "123"
2. Converting Float to String
Python
b = 45.67
repr_b = repr(b)
print(repr_b)
3. Converting List to String
Python
d = [1, 2, 3]
repr_d = repr(d)
print(repr_d)
4. Converting Dictionary to String
Python
e = {"name": "Alice", "age": 25}
repr_e = repr(e)
print(repr_e)
Output{'name': 'Alice', 'age': 25}
Using __str__() Method
The __str__() method is used to define how an object of a custom class is converted into a string when str() is called on it. This method is part of Python’s object-oriented programming, and it allows us to control the string representation of our own classes.
Python
class MyClass:
def __str__(self):
return "I am a custom object!"
obj = MyClass()
str_obj = str(obj)
print(str_obj)
OutputI am a custom object!
Using __repr__() Method
The __repr__() method is used to define how an object of a custom class is converted into a string when repr() is called. Like __str__(), it is a special method, but it is aimed at providing a more detailed or formal representation of the object for debugging or logging purposes.
Python
class MyClass:
def __repr__(self):
return "MyClass()"
obj = MyClass()
repr_obj = repr(obj)
print(repr_obj)
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice