How To Convert Object To String In Python

It’s essential to understand how to change an object into a string when using Python. We frequently need to transform an object to a string when logging data or reporting objects to the terminal, among other uses.

In this blog post, we will look at the many Python methods for converting an object to a string. We will go over the benefits and drawbacks of each technique and provide usage examples.

At the end of this article, you will have a better understanding of how to convert objects to strings in Python and which approach suits your needs the most.

Need to convert object to string in python

There are several reasons why we might need to convert an object to a string in Python:

  1. Printing and logging: Most of the time, we prefer to see data in string form when printing or logging it. The value of an object can be quickly displayed by converting it to a string.
  • String manipulation: We might occasionally need to work with strings. We can apply string operations to an item by turning it into a string.
  • Interoperability: When working with different systems or programming languages, it is common to exchange data in string form. Converting an object to a string allows us to easily exchange data with other systems.
  • Serialization: An object is transformed into a format that can be stored or conveyed through the process of serialisation. This format is frequently a string. We can serialise an object by converting it to a string.

Different methods to convert an object to string

There are various ways to convert an object to a string in Python. Here are some of the common approaches:

  1. Using str() function
  2. Using repr() function
  3. Using format() function
  4. Using f-strings

Detailed Explanation:

1. Using str() function to change object to string:

A string can be created from an object using the str() function. It gives back a string that represents the object. When an object needs to be represented as a human-readable string, this method is helpful. Integers, floats, lists, tuples, and dictionaries can all be converted to strings using the str() function.

Sample Code:

num = 42
str_num = str(num)
print(str_num)

Output:

'42'

Explanation of Code:

  1. num is a variable that stores the integer value 42.
  2. str() is a built-in function in Python that converts a value to its string representation.
  3. str_num will contain the string “42”.
  4. The output of this code will be the string “42”.

2. Change object into string using repr() function:

Objects can be represented by strings by using the repr() method to transform them from objects to strings. When you require a string representation of an object so that you can replicate it, this technique comes in handy. Any objects, including dictionaries, lists, tuples, floats, integers, and float-type objects, can be converted to strings using the repr() function.

Sample Code:

num = 42
repr_num = repr(num)
print(repr_num)

Output:

42

Explanation of Code:

  1. num is assigned a value of 42
  2. repr_num is assigned a string representation of the integer value of num using the repr() function
  3. The print() function is called to output the value of repr_num to the console

3. Using format() function convert object to string:

The format() function is used to format strings in Python. It can also be used to convert an object to a string. The format() function takes the object as an argument and returns a string representation of the object. This method is useful when you need to format the output of an object as a string.

Sample Code:

name = "John"
age = 30
info = "My name is {} and I am {} years old".format(name, age)
print(info)

Output:

My name is John and I am 30 years old

Explanation of Code:

  1. The variable name is assigned the string value “John”.
  2. The variable age is assigned the integer value 30.
  3. The format() method is called on the string “My name is {} and I am {} years old”, which contains two placeholders {} for values to be inserted.
  4. The resulting string is assigned to the variable info.
  5. The print() function is called with the variable info as an argument.

4. Objects to string conversion using f-strings:

f-strings are a new feature in Python 3.6 and later versions that allow you to embed expressions inside string literals. You can use f-strings to convert an object to a string. The f-strings are a more concise and readable way to format strings than the format() function.

Sample Code:

name = "John"
age = 30
info = f"My name is {name} and I am {age} years old"
print(info)

Output:

My name is John and I am 30 years old

Explanation of Code:

  1. name is a string variable that contains the name “John”
  2. age is an integer variable that contains the value 30
  3. info is assigned the value of an f-string that includes the values of name and age in a sentence

Best out of four methods

str() is a built-in function in Python that is specifically designed to convert an object to a string.

  1. It is a simple and straightforward method that is easy to use.
  2. It works for most data types and can convert integers, floats, lists, tuples, dictionaries, and other objects to a string.
  3. The resulting string is usually human-readable and easy to understand.
  4. It is widely used in Python code and is a standard method for converting objects to strings.
  5. Other methods, such as repr(), format(), and f-strings, have their own advantages, but they may not always be the best choice for converting objects to strings depending on the specific use case.

Sample Problems:

Problem 1: Create a class called Student with attributes name, age, and grade. Write a Python program that reads a list of Student objects from a file and prints each student’s information as a string using str() method.

Solution:

  1. We first define a class called Student with attributes name, age, and grade.
  2. We define the __init__() method to initialize the attributes of the class.
  3. We define the __str__() method to return a string representation of the class.
  4. We define an empty list students to store the objects of the Student class.
  5. We use the open() function to read the list of student objects from a file.
  6. For each line in the file, we extract the name, age, and grade data and create a new Student object.
  7. We append the new Student object to the students list.
  8. Finally, we loop through the students list and print each object as a string using the str() method.

Code:

class Student:
#define dictionary or object
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade
    
    def __str__(self):
        return f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}"

# read from file and store in student array        
students = []
with open("students.txt", "r") as file:
    for line in file:
        data = line.strip().split(",")
        name, age, grade = data[0], int(data[1]), data[2]
        students.append(Student(name, age, grade))
 
#display output       
for student in students:
    print(str(student))

Output:

Assuming the contents of the students.txt file are as follows:

John,18,A
Jane,17,B

The program will output:

Name: John, Age: 18, Grade: A
Name: Jane, Age: 17, Grade: B

Problem 2: Write a Python program that calculates the area of different shapes. Define classes for Circle, Rectangle, and Square, each with a method to calculate its area. Then, create a list of shapes and print their areas as strings using repr() method.

Solution:

  1. We start by defining three classes: Circle, Rectangle, and Square. Each class has an area() method that calculates the area of the shape.
  2. The __repr__() method is also defined for each class, which returns a string that represents the object. We use repr() method in this problem, so we need to define __repr__() method.
  3. Then, we create a list of shapes, which includes one Circle, one Rectangle, and one Square object.
  4. We iterate through the list of shapes and print the area of each shape as a string, using the repr() method to display the object.

Code:

import math

#create class for circle and define area formulas 
class Circle:
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return math.pi * self.radius ** 2
    
    def __repr__(self):
        return f"Circle({self.radius})"
    
#create class for reactangle and define area formulas for it
class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
    
    def area(self):
        return self.length * self.width
    
    def __repr__(self):
        return f"Rectangle({self.length}, {self.width})"
    

class Square:
    def __init__(self, side):
        self.side = side
    
    def area(self):
        return self.side ** 2
    
    def __repr__(self):
        return f"Square({self.side})"

shapes = [Circle(5), Rectangle(4, 6), Square(3)]

#display output after converting it to string using f string().
for shape in shapes:
    print(f"The area of {repr(shape)} is {shape.area()}.")

Output:

The area of Circle(5) is 78.53981633974483.
The area of Rectangle(4, 6) is 24.
The area of Square(3) is 9.

Problem 3: Write a Python program that reads a list of numbers from a file and calculates their average. Then, print the average as a string using format().

Solution:

  1. Using the open() method, open the file “numbers.txt” in read mode, and then assign it to the variable f.
  2. List comprehension is used to read the file’s lines, and int is used to transform each line to an integer (). This generates a collection of integers known as numbers.
  3. Using the sum() function to add up all the numbers in the list and the len function to divide by the list’s length will yield the average of the numbers (). Give the variable average this value.
  4. Using the format() method, which inserts the average’s value into the string at the point of, print the average as a string.

Code:

with open('numbers.txt', 'r') as f:
    numbers = [int(line.strip()) for line in f]

#formula for average
average = sum(numbers) / len(numbers)

#display output
print("The average of the numbers is: {}".format(average))

Output:

The average of the numbers is: 53.6

Problem 4: Create a programm that reads a file containing a list of book titles and authors and stores them as a list of tuples. Use the f strings() method to output the list as a string after that.

Solution:

  1. First, we open the file containing the list of book titles and authors using the open() function and the with statement. This ensures that the file is properly closed after we’re done with it.
  2. We create an empty list called books to store the book titles and authors.
  3. We loop through each line in the file using a for loop. For each line, we strip any whitespace using the strip() method and then split the line into a list using the split() method with a comma as the delimiter. We assume that the first element of the list is the book title and the second element is the author.
  4. We create a tuple with the book title and author using parentheses and then append it to the books list.
  5. Finally, we loop through the books list using a for loop and print each book title and author using f-strings. The f at the beginning of the string allows us to embed expressions (such as the book title and author) inside curly braces {}.

Code:

# Open the file containing the list of book titles and authors
with open("books.txt", "r") as file:
    # Create an empty list to store the book titles and authors
    books = []
    # Loop through each line in the file
    for line in file:
        # Split the line by the delimiter (in this case, a comma)
        book_info = line.strip().split(",")
        # Create a tuple with the book title and author and append it to the list
        books.append((book_info[0], book_info[1]))

# Print the list of books using f-strings
for book in books:
    print(f"Book Title: {book[0]}, Author: {book[1]}")

Output:

Sample data in file:

The Catcher in the Rye, J.D. Salinger
To Kill a Mockingbird, Harper Lee
1984, George Orwell
The Great Gatsby, F. Scott Fitzgerald
Pride and Prejudice, Jane Austen

Sample output:

Book Title: To Kill a Mockingbird, Author: Harper Lee
Book Title: 1984, Author: George Orwell
Book Title: Pride and Prejudice, Author: Jane Austen

Conclusion:

In conclusion, converting an object to a string is a frequent requirement when working with Python. There are several methods to achieve this, including str(), repr(), format(), and f-strings.

Each method has its advantages and disadvantages, and the choice of method will depend on the specific use case. It is recommended to use the str() function as it is the most straightforward and widely used method for converting an object to a string.

However, it is essential to keep in mind the data type of the object and the formatting requirements of the output string. By mastering these methods, you can convert any object to a string in Python with ease.