Python is a powerful programming language that is widely used in various domains such as web development, data science, machine learning, and more.
One of the common tasks in Python development is printing objects as strings, which can be useful in debugging or displaying information to the user. In this tutorial, we will learn how to print objects as strings in Python.
Steps:
1. Convert Object to String using str() Function
The str() function in Python converts an object to its string representation. This is the simplest method to print an object as a string. We can simply pass the object to the str() function and it will return its string representation.
1 2 3 |
# Example my_object = {'name': 'John'} print(str(my_object)) |
The output will be:
"{'name': 'John'}"
2. Convert Object to String using repr() Function
The repr() function in Python returns a string that can be used to recreate the object. It is mostly used for debugging and generating source code. We can pass the object to the repr() function and it will return a string representation.
1 2 3 |
# Example my_object = {'name': 'John'} print(repr(my_object)) |
The output will be:
"{'name': 'John'}"
3. Implement the __str__() and __repr__() Methods
In Python, we can define the __str__() and __repr__() methods on the object to specify how it should be represented as a string. The __str__() method is called when str() is used on the object, while the __repr__() method is called when repr() is used on the object.
1 2 3 4 5 6 7 8 9 10 11 |
# Example class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name} ({self.age})" def __repr__(self): return f"Person(name='{self.name}', age={self.age})" |
With the __str__() and __repr__() methods, we can now easily print the object as a string with the str() and repr() functions.
1 2 3 4 |
# Example person = Person('John', 25) print(str(person)) print(repr(person)) |
The output will be:
"John (25)" "Person(name='John', age=25)"
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# Example Code my_object = {'name': 'John'} print(str(my_object)) print(repr(my_object)) class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name} ({self.age})" def __repr__(self): return f"Person(name='{self.name}', age={self.age})" person = Person('John', 25) print(str(person)) print(repr(person)) |
Output:
{'name': 'John'} {'name': 'John'} <__main__.Person object at 0x00000221888F9E50> <__main__.Person object at 0x00000221888F9E50>
Conclusion
Printing an object as a string in Python is a common task that can be achieved using the str() and repr() functions, or by defining the __str__() and __repr__() methods on the object.
By understanding these concepts, you can easily manipulate object data in Python programming.