Bird
Raised Fist0
Pythonprogramming~20 mins

String representation methods in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
String Representation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of __str__ vs __repr__
What is the output of the following code?
Python
class Fruit:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return f"Fruit: {self.name}"
    def __repr__(self):
        return f"Fruit('{self.name}')"

f = Fruit('Apple')
print(str(f))
print(repr(f))
A
Fruit: Apple
Apple
B
Fruit('Apple')
Fruit: Apple
C
Apple
Fruit('Apple')
D
Fruit: Apple
Fruit('Apple')
Attempts:
2 left
💡 Hint
Remember __str__ is for user-friendly display, __repr__ is for developer-friendly output.
Predict Output
intermediate
2:00remaining
Using __repr__ in a list
What is the output of this code?
Python
class Animal:
    def __init__(self, species):
        self.species = species
    def __repr__(self):
        return f"Animal('{self.species}')"

animals = [Animal('Cat'), Animal('Dog')]
print(animals)
A[Animal('Cat'), Animal('Dog')]
B['Cat', 'Dog']
C[Animal(Cat), Animal(Dog)]
D[<Animal object>, <Animal object>]
Attempts:
2 left
💡 Hint
Lists use __repr__ of their elements when printed.
🔧 Debug
advanced
2:00remaining
Fix the __str__ method to avoid error
This code raises an error when printing the object. Which option fixes the error?
Python
class Book:
    def __init__(self, title):
        self.title = title
    def __str__(self):
        return 'Book title is ' + self.title.upper

b = Book('Python 101')
print(b)
A
def __str__(self):
    return 'Book title is ' + self.title.upper()
B
def __str__(self):
    return 'Book title is ' + str(self.title.upper)
C
def __str__(self):
    return 'Book title is ' + self.title.upper
D
def __str__(self):
    return 'Book title is ' + self.title
Attempts:
2 left
💡 Hint
Check if you are calling the method or just referencing it.
🧠 Conceptual
advanced
2:00remaining
Difference between __str__ and __repr__
Which statement best describes the difference between __str__ and __repr__ methods in Python?
A<code>__str__</code> is only used when printing lists; <code>__repr__</code> is used everywhere else.
B<code>__str__</code> is for a readable string for users; <code>__repr__</code> is for unambiguous string for developers.
CBoth methods return the same string but <code>__repr__</code> is faster.
D<code>__repr__</code> is for readable string for users; <code>__str__</code> is for debugging.
Attempts:
2 left
💡 Hint
Think about who the string is for: user or developer.
Predict Output
expert
2:00remaining
Output of custom __repr__ with eval
What is the output of this code?
Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return f"Point({self.x}, {self.y})"

p = Point(3, 4)
q = eval(repr(p))
print(p == q)
print(q)
A
False
&lt;__main__.Point object at 0x...&gt;
B
True
Point(3, 4)
C
False
Point(3, 4)
D
True
&lt;__main__.Point object at 0x...&gt;
Attempts:
2 left
💡 Hint
Does eval(repr(p)) create an equal object? What about equality check?

Practice

(1/5)
1. Which method in Python is used to define the informal string representation of an object, typically for end users, and is called by the print() function?
easy
A. __init__
B. __repr__
C. __str__
D. __del__

Solution

  1. Step 1: Understand the purpose of __str__

    The __str__ method returns a readable string for users, used by print().
  2. Step 2: Compare with __repr__

    The __repr__ method returns a detailed string for developers, not usually for printing.
  3. Final Answer:

    __str__ -> Option C
  4. Quick Check:

    Informal string for print() = __str__ [OK]
Hint: Use __str__ for user-friendly print output [OK]
Common Mistakes:
  • Confusing __repr__ with __str__
  • Thinking __init__ controls string output
  • Assuming __del__ affects printing
2. Which of the following is the correct syntax to define the __repr__ method inside a Python class?
easy
A. def __repr__(self): self.return 'object info'
B. def repr(self): return 'object info'
C. def __repr__(self): print('object info')
D. def __repr__(self): return 'object info'

Solution

  1. Step 1: Check method name and parameters

    The method must be named __repr__ and take self as parameter.
  2. Step 2: Verify return statement

    __repr__ must return a string, not print or use invalid syntax.
  3. Final Answer:

    def __repr__(self): return 'object info' -> Option D
  4. Quick Check:

    Correct __repr__ syntax returns string [OK]
Hint: __repr__ must return a string, not print it [OK]
Common Mistakes:
  • Omitting underscores in __repr__
  • Using print instead of return
  • Wrong method name without underscores
3. What is the output of this code?
class Cat:
    def __repr__(self):
        return 'Cat()'
    def __str__(self):
        return 'A cute cat'

c = Cat()
print(c)
print(repr(c))
medium
A. A cute cat Cat()
B. Cat() A cute cat
C. A cute cat A cute cat
D. Cat() Cat()

Solution

  1. Step 1: Understand print(c) calls __str__

    The print(c) calls __str__, which returns 'A cute cat'.
  2. Step 2: Understand print(repr(c)) calls __repr__

    The repr(c) calls __repr__, which returns 'Cat()'.
  3. Final Answer:

    A cute cat Cat() -> Option A
  4. Quick Check:

    print() = __str__, repr() = __repr__ [OK]
Hint: print() uses __str__, repr() uses __repr__ [OK]
Common Mistakes:
  • Mixing __str__ and __repr__ outputs
  • Assuming print calls __repr__
  • Confusing repr() with str()
4. Identify the error in this class definition related to string representation methods:
class Dog:
    def __str__(self):
        return 'Dog'
    def __repr__(self):
        print('Dog object')

print(Dog())
medium
A. __repr__ should return a string, not print it
B. __str__ method is missing self parameter
C. print(Dog()) should be print(Dog)
D. __repr__ method name is incorrect

Solution

  1. Step 1: Check __repr__ method body

    The __repr__ method uses print() instead of returning a string, which is incorrect.
  2. Step 2: Understand consequences

    Because __repr__ returns None, printing the object calls __str__ but repr() would fail to give a string.
  3. Final Answer:

    __repr__ should return a string, not print it -> Option A
  4. Quick Check:

    __repr__ must return string, not print [OK]
Hint: Always return string in __repr__, never print [OK]
Common Mistakes:
  • Using print instead of return in __repr__
  • Forgetting self parameter in methods
  • Confusing print(Dog()) with print(Dog)
5. You want to create a class Book where print(book) shows the title nicely, but repr(book) shows a string that can recreate the object. Which implementation correctly achieves this?
class Book:
    def __init__(self, title):
        self.title = title

    def __str__(self):
        return f"Book titled '{self.title}'"

    def __repr__(self):
        # Which line below is correct?
        pass
hard
A. return f"Book('{self.title}')"
B. return f"Book(title='{self.title}')"
C. return f"Book(title={self.title})"
D. return f"Book({self.title})"

Solution

  1. Step 1: Understand __str__ output

    The __str__ method returns a user-friendly string with the title.
  2. Step 2: Create __repr__ that recreates object

    The __repr__ should return a string that looks like the constructor call with a keyword argument and quotes around the title.
  3. Step 3: Check options for correct syntax

    return f"Book(title='{self.title}')" returns Book(title='title') which can be used to recreate the object. Others miss quotes or keyword.
  4. Final Answer:

    return f"Book(title='{self.title}')" -> Option B
  5. Quick Check:

    __repr__ returns constructor call string [OK]
Hint: __repr__ should return code to recreate object [OK]
Common Mistakes:
  • Missing quotes around string in __repr__
  • Not using keyword argument in __repr__
  • Returning informal string in __repr__