
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Object to Expression String in Python
What's an Expression?
In Python, an expression is any statement that evaluates to a value when executed.
<<< 4 + 6 10 <<< 22172 * 27282 604896504 <<< max(12, 9330) 9330
We can evaluate a valid Python expression using the eval() function. We can print the Python expressions using the printable characters.
print(eval("4 + 6")) print(eval("22172 * 27282")) print(eval("max(12, 9330)"))
Converting an Object to an Expression String
The given task is to convert an object to an expression (string) i.e., we need to convert the contents of the Python object to a printable string. We can achieve this using the following -
-
Using the repr() Function
-
Using the str() Function
-
By creating the Custom repr() Function
Using the repr() Function
The repr() function accepts a Python object as a parameter and returns the string representation of it. We will be able to evaluate the string returned by this function using the eval() function.
The string returned by this function is more detailed and unambiguous than the one which is returned by the str() function. We can define our own __repr__() function to control its output.
Example
This converts a list [3, 2, 1] into a string representation using repr(). The eval() interprets the string back into a list. This determines the copied object, which determines the original structure. This confirms the transformation first as a string and then as a list.
x = [3, 2, 1] expr_str = repr(x) print(expr_str) x_copy = eval(expr_str) print(x_copy)
The result is obtained as follows -
[3, 2, 1] [3, 2, 1]
Using str() Function
The str() in Python accepts an object as a parameter and returns the string version of the given object.
Example
In the following example we are retrieving the current date using the datetime.now() and converting it into a string.
import datetime today = datetime.datetime.now() print(str(today))
We will get the result as follows -
{'a': 2, 'b': 4}
For Custom Object
We are defining a point class with attributes a and b. the __repr__() method formats its string representation. Creating p = Point(4, 5), calling repr() generates the outputs, this shows the object's expression-like representation.
class Point: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return f"Point({self.a}, {self.b})" p = Point(4, 5) expr_str = repr(p) print(expr_str)
The result is obtained as follows -
Point(4, 5)