In Python, the built-in functions str() and repr() are both used to convert objects into their string representations, but they serve distinct purposes. The str() function in Python is intended to produce a readable and user-friendly representation of an object, making it suitable for display to end users. On the other hand, the repr() function in Python generates a more detailed and unambiguous string, often resembling valid Python code, which is especially useful for debugging and logging. In this article, we will learn about the key differences between str() and repr() with examples, use cases, and performance comparisons.
Table of Contents:
What is str() in Python?
The str() function in Python converts the data into a presentable format. It is a built-in function used for converting various data types into their readable Python string representations. It helps you to see the readable version of numbers, lists, or other objects as plain text. It is quite helpful for displaying data and helps combine data of different types in the print statement.
Example:
Output:
Explanation: Here, the str() function in Python converts the string into a format that is easy to read. It also doesn’t contain extra details like quotes and /n prints the second word on the next line.
Top Benefits of Using str() in Python for Readable Output
- The str() function in Python can convert integers, floats, lists, tuples, dictionaries, and even custom objects into Python string representations.
- When writing non-string data to a file, str() ensures the content is in the correct format.
- It can take an encoding format as an argument for byte conversions.
Master Python Course and Unlock Your Career
Explore Python Course
What is repr() in Python?
The repr() function in Python is used to create a Python string representation of the specified object. This means it can be used to recreate the object. The repr() function in Python is mainly used for debugging, as it helps the developers to see the exact value and format of the objects in the code without changing them.
Example:
Output:
Explanation: Here, repr() function in Python also includes quotes to show you that it is a string, which is useful for debugging because it gives more precise information. Which is a behaviour that str() does not have.
Why Use repr() in Python – Key Benefits for Debugging
- The repr() function in Python returns a string that, when passed to eval(), can ideally recreate the original object. This makes debugging and logging more efficient.
- When debugging, you often need an accurate description of objects. repr() provides a clear, precise view of an object’s internals, making it easier to track issues.
- For user-defined classes, implementing __repr__() allows better debugging and logging.
str() vs repr() in Python DateTime Objects – Example & Output
This table explains the difference between str and repr in Python by showing their outputs on a datetime object. It also highlights the str vs repr in Python behaviour for complex objects.
Example:
Output:
Explanation: Here, while str(today) prints the date in a way that is easy for you to read, repr(today) would give you the full details, including the class name.
How to Override repr and str in Python Custom Classes?
Overriding str() and repr() allows you to define how your custom class instances should appear when passed to the str() function or repr() function.
Example:
Output:
Explanation: Here, the str(p) proves more useful to users, while repr(p) helps developers like you to understand how the object is created.
How str() and repr() Affect Python Print Statements?
In Python, the print() function internally uses the str() function to display output. However, if you explicitly use repr() within a print statement, it will show a more detailed and developer-friendly representation of the object.
These are the examples that affect the output:
1. Default Behaviour of print() (uses str()):
Example:
Output:
Explanation: print() uses str(), so the newline character n is interpreted and rendered as an actual line break.
2. Explicit Use of repr() in print():
Example:
Output:
Explanation: repr() reveals the raw string, including escape characters and surrounding quotes.
3. Custom Objects and print():
If your object has both __str__() and __repr__() methods defined.
Example:
Output:
Explanation: Here, this code shows that even if both str() and repr() are in the print function, it will always call str() to print the output.
Why is repr() Important for Debugging?
During the process of writing code, debugging is an essential part of making sure everything works perfectly. Using the two functions repr() and str() can help in showing details of an object, help recreate the object when debugging, and also provide more accuracy than the str() function in Python.
Example:
Output:
Explanation: Here, the repr() function in Python is more useful for complex objects like custom classes and lists.
Comparing str() vs repr() in Python Logging Systems
Feature |
str() |
repr() |
Purpose |
Provides a user-friendly, readable string |
Provides an unambiguous, developer-friendly string |
Used For |
Displaying output to end users |
Debugging and detailed logging |
Output Format |
Simplified and clean |
Exact, includes escape characters and quotes |
Default in print() |
Yes |
No, must be called explicitly |
Suitable for Logs |
For brief or user-facing logs |
For technical, diagnostic logs |
Custom Class Usage |
Calls __str__() method |
Calls __repr__() method |
Reconstructing Object |
Not always possible |
Often returns a string that can recreate the object |
Example Output for String |
HellonWorld → Hello and World on separate lines |
'Hello\nWorld' → full raw string with escape characters |
Get 100% Hike!
Master Most in Demand Skills Now!
The functions str() and repr() operate differently when used with different data types, like floats, integers, or lists. This table compares the performance of the str() and repr() functions in Python.
Example 1 (numbers):
Output:
Explanation: In the case of numbers, both the functions str() and repr() return the same output because no ambiguity exists between their representations.
Example 2 (Lists):
Output:
Explanation: In this case, the list data type already has a structure. The functions str() and repr() return the same output. In some complex cases, repr() can save more accurate details.
Using repr() vs str() for Data Serialization in Python
Data serialisation is the process of converting Python objects to JSON. In this case, the repr() function in Python may be more useful than the str() function, as we need a more accurate object representation.
Example:
Output
Explanation: Here, the str() function, as usual, gives a much more human-readable output but loses accuracy in nested objects. The repr() keeps the exact structure. Hence, it is more suitable for sterilisation.
How to Override repr and str in Python Custom Classes
While creating custom classes, the str() and repr() functions can be defined by implementing __str()__ and __repr()__ methods in the code.
Example:
Output:
Explanation: Here also the __str()__ gives a readable summary while the __repr()__ gives the exact representation, helping developers learn how to recreate the object.
Key Differences Between str() vs repr()
Feature |
str() |
repr() |
Purpose |
The str() function is designed to be more readable and simpler to understand. |
This function is designed to give an exact representation of an object, which is useful for debugging. |
Output |
Creates a user-friendly string format that is simplified. |
Creates a precise output that can be copy pasted back into the code |
Quotes in Strings |
This function doesn’t involve quotes around a string. |
Always carries quotes to show exact representation. |
Best Use |
This function is ideal for presenting information to users in a readable format. |
Ideal for debugging and logging when an object representation is needed. |
Real-World Use Cases of str() and repr() in Python Logging
1. Logging System
To print a clear message and full log details for debugging.
Example:
Output:
Explanation: Here, the str(tx) gives you a readable output, while the repr(tx) provides you with the detailed information for useful debugging and logging.
2. Chat Application Logging
To display the chat message and the logs of the user with the exact date and time.
Output:
Explanation: Here, the str(msg) gives the readable chat message, while the repr(msg) provides detailed information that is useful for debugging and logging.
Unlock Your Future in Python
Start your Python Journey for Free Today
Conclusion
In conclusion, both str() and repr() serve important but different roles in Python. Use str() when you want to present data in a clean, readable format ideal for end-user output. Use repr() when you need a more precise, unambiguous string that helps with debugging or recreating objects. Choosing the right one based on the need can make your code clearer, more maintainable, and easier to debug.
Further, check out our Python certification course and get ready to excel in your career with our Basic Python interview questions prepared by experts.
Single vs Double Underscores in Python – Explore the distinctions between single and double underscores in Python in this article.
Print Without Newline in Python – Here, techniques to print without newline characters in Python are explained.
Open a File in Python – Here, the steps to open a file in Python are described.
Close a File in Python – Here, methods for closing files in Python are discussed.
Extract File Extension – Here, methods to retrieve file extensions from filenames are discussed.
Python Split String Into List – Here, the process of splitting strings into lists in Python is described.
str() vs repr() in Python – FAQs
Q1. Can str() and repr() return the same value?
Yes, str() and repr() will return the same value for some objects, like numbers. For example, when you write print(str(100)) and in the next line enter print(repr(100)).
Q2. What happens if a class doesn't have str() or repr()?
If a class does not have __str__() or __repr__(), Python will use the default representation, which looks something like this: <__main__.ClassName object at 0x7f8b3c5d8>.
Q3. Can repr() be used for all objects?
Yes, this method can be used for any object in Python. It will try to return a valid Python expression.
Q4. Why does repr() include quotes in strings?
The need for quotes is that they show the value of a string, helping developers see the exact format of the data.
Q5. Which function should I use for logging?
You can use the repr() function because it makes debugging easier.