When you program in Python, there are several times when you’ll come across several functions performing in a very similar manner. The str() function helps in printing user-friendly, simple output, and the repr() is used to show the detailed output for the developers, which helps with debugging. Knowing when to use these functions will help make your code more readable and debuggable. This blog will provide differences between str() and repr(), when to use each function, best use case, how they work in built-in and user-defined classes, etc.
Table of Contents:
What is str() in Python?
When you print something using str() in Python, the function converts it into a presentable format. It is a built-in function used for converting various data types into their 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 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 in the next line.
Advantages of using str() in Python
- The str() function can convert integers, floats, lists, tuples, dictionaries, and even custom objects into 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() as a function is used to create a string representation of the specified object. This means it can be used to recreate the object. The repr() function 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() 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.
Advantages of using repr() in Python
- The repr() function 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.
Using str() and repr() with Date Time
Here you’ll see how these functions behave when we use them on a date and time object.
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.
Using str() and repr() in Your Own Class
In this case, you can also define how the str() and repr() functions should behave, which helps in better debugging.
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.
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 str().
For example:
Output:
Explanation: Here, the repr() is more useful for complex objects like custom classes and lists.
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
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.
Data Sterilization Using repr() vs str()
Data sterilization is the process of converting Python objects to JSON. In this case, repr() may be more useful than the str() function as we need a more accurate object representation.
Example:
Output
Explanation: Here, 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 sterilization.
Customization of repr() and str() in Your Own 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() and 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 Example
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
We can conclude from the above examples that using str() is better when you want a simple, easy-to-read output, while you can use repr() when you need an exact and detailed representation of an object. Knowing when to use which function will make your Python code clearer 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.
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.