Python print object as string

How To Print An Object As A String In Python

To print an object as a String in Python, you can print the desired attributes by the dot or the __repr__(), __str__() method. Follow the explanation below to understand better.

Using a dot

To print an object as a String in Python, you can use a dot and print the specified attributes of the object that you want.

Look at the example below.

# Create a class. class Country: def __init__(self, name=str(), capital=str(), population=0, area=0): self.name = name self.capital = capital self.population = population self.area = area # Create a new object. country = Country('Vietnam', 'Ha Noi', 96, 333) # Print attributes of an object with the dot. print('Name: <>\nCapital: <>\nPopulation: <>\nArea: <>'.format(country.name, country.capital, country.population, country.area))
Name: Vietnam Capital: Ha Noi Population: 96 Area: 333

Using the __repr__() method

Besides using the dot, you can print an object as a String by overriding the __repr__() method.

Look at the example below.

# Create a class. class Country: def __init__(self, name=str(), capital=str(), population=0, area=0): self.name = name self.capital = capital self.population = population self.area = area # Override the __repr__() method. def __repr__(self): result_str = 'Name: <>\nCapital: <>\nPopulation: <>\nArea: <>'.format( self.name, self.capital, self.population, self.area) return result_str # Create a new object. country = Country('Vietnam', 'Ha Noi', 96, 333) # Print attributes of an object with the repr() method. print(repr(country))
Name: Vietnam Capital: Ha Noi Population: 96 Area: 333

Using the __str__() method

In addition, you can override the __str__() method to print an object as a String in Python. After that, you can print an object by calling its name.

Читайте также:  E katalog ru ek item php

Look at the example below.

# Create a class. class Country: def __init__(self, name=str(), capital=str(), population=0, area=0): self.name = name self.capital = capital self.population = population self.area = area # Override the __str__() method. def __str__(self): result_str = 'Name: <>\nCapital: <>\nPopulation: <>\nArea: <>'.format(self.name, self.capital, self.population, self.area) return result_str # Create a new object. country = Country('Vietnam', 'Ha Noi', 96, 333) # Print attributes of an object with the __str__() method. print(country)
Name: Vietnam Capital: Ha Noi Population: 96 Area: 333

Summary

We have shown you how to print an object as a String in Python in 3 ways. Personally, you should override the __str__() method to achieve your goal because you can print an object by calling its name after overriding the __str__() method. Leave your comment below if you have any questions about this tutorial. Thanks!

My name is Thomas Valen. As a software developer, I am well-versed in programming languages. Don’t worry if you’re having trouble with the C, C++, Java, Python, JavaScript, or R programming languages. I’m here to assist you!

Name of the university: PTIT
Major: IT
Programming Languages: C, C++, Java, Python, JavaScript, R

Источник

Python print object as a string | Example code

Use str() and __repr()__ methods to print objects as a string in Python. The __str__ method is what gets called happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt).

Python print an object as a string example

Using str() method

# object of int a = 99 # object of float b = 100.0 # Converting to string s1 = str(a) print(s1) print(type(s1)) s2 = str(b) print(s2) print(type(s2)) 

Python print object as a string

Use repr() to convert an object to a string

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

If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__ , Python will use what you see above as the __repr__ , but still use __str__ for printing.

class Test: def __repr__(self): return "Test()" def __str__(self): return "Member of Test" t = Test() print(t)

Output: Member of Test

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this object tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Источник

Python print object as string

Last updated: Feb 21, 2023
Reading time · 4 min

banner

# 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

convert object to string

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

make sure to return string from str method

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) # 👉️ ''

convert class instance to json string

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.

Источник

Оцените статью