How to Convert an Object to a String in Python?

In this tutorial, I will explain how to convert an object to a string in Python. As a Python developer working on a project for a US-based company, I recently encountered a situation where I needed to convert an object to a string format. I explored more about this topic and I will share my findings in this article with examples and screenshots of executed example code.

Objects in Python

In Python, everything is an object. This means that all built-in data types, such as integers, floats, lists, and dictionaries, are objects. Each object has its attributes and methods that define its behavior.

Read How to Swap Characters in a String Using Python?

Convert Objects to Strings in Python

There are several ways to convert an object to a string in Python. Let’s explore the most common methods:

1. Use the str() Function

The str() function is a built-in Python function that takes any data type and converts it into a string. Here’s an example:

age = 25
name = "John Doe"
print(str(age))  
print(str(name))  

Output:

25
John Doe

I have executed the above example code and added the screenshot below.

Convert an Object to a String in Python

In this example, we have an integer age and a string name. By passing these objects to the str() function, we convert them to strings.

Read How to Convert a String to ASCII in Python?

2. Use the repr() Function

The repr() function is similar to str() in Python, but it returns a string representation of an object that is suitable for debugging and development purposes. It provides a more detailed representation of the object. Here’s an example:

person = {"name": "Alice Smith", "age": 30, "city": "New York"}
print(repr(person))  

Output:

{'name': 'Alice Smith', 'age': 30, 'city': 'New York'}

I have executed the above example code and added the screenshot below.

How to Convert an Object to a String in Python

In this example, we have a dictionary person representing a person’s details. Using the repr() function, we obtain a string representation of the dictionary that includes the key-value pairs.

Read How to Generate a Random String of a Specific Length in Python?

3. Define the str() Method

In Python, you can define a special method called __str__() within a class to provide a custom string representation of objects of that class. Here’s an example:

class Customer:
    def __init__(self, name, email):
        self.name = name
        self.email = email

    def __str__(self):
        return f"Customer(name='{self.name}', email='{self.email}')"

customer = Customer("Bob Johnson", "bob@example.com")
print(str(customer)) 

Output:

Customer(name='Bob Johnson', email='bob@example.com')

I have executed the above example code and added the screenshot below.

Convert an Object to a String in Python str()

In this example, we define a Customer class with a custom __str__() method. When we pass an instance of the Customer class to the str() function, it invokes the __str__() method and returns the specified string representation.

Read How to Check if a String is a Valid UUID in Python?

Dealing with Pandas DataFrames

When working with Pandas DataFrames, you might encounter columns with the object data type. To convert these columns to strings, you can use the astype() function. Here’s an example:

import pandas as pd

data = {"name": ["Emma Davis", "Liam Wilson"], "age": [28, 35]}
df = pd.DataFrame(data)
df["name"] = df["name"].astype(str)
print(df.dtypes)  # Output: name    object
                  #         age      int64
                  #         dtype: object

In this example, we create a Pandas DataFrame df with a “name” column of type object. By using the astype(str) function, we convert the “name” column to a string data type.

Read How to Shuffle Characters in a String using Python?

Conclusion

In this tutorial, I have explained how to convert an object to a string in Python. I discussed using the str() function, repr() function, defining custom __str__() methods, and using the astype() function for Pandas DataFrames, you can effectively convert objects to strings in Python.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.