str() And repr()

Stringification And Representation

  • str(obj): nicely made-up string, used by e.g. print()

  • repr(obj): object representation, ideally suitable as eval() input

  • Default: prints something useless (class name and object identity)

    class Person:
        def __init__(self, firstname, lastname):
            self.firstname = firstname
            self.lastname = lastname
    
    person = Person('Joerg', 'Faschingbauer')
    
  • Expicitly calling str() on object

    str(person)
    
    '<__main__.Person object at 0x7f62a7d973b0>'
    
  • Using print() with an object calls str() on is own

    print(person)
    
    <__main__.Person object at 0x7f62a7d973b0>
    
  • repr() on an object

    repr(person)
    
    '<__main__.Person object at 0x7f62a7d973b0>'
    
  • print() a list of objects ⟶ uses repr() on list elements

    print([person])
    
    [<__main__.Person object at 0x7f62a7d973b0>]
    

Overloading str() And repr(): __str__(), __repr__()

  • __str__(): returns human readable string, describing the object. Called, for example, by print().

  • __repr__(): object representation. Usually the code to re-construct the object.

    class Person:
        def __init__(self, firstname, lastname):
            self.firstname = firstname
            self.lastname = lastname
    
        def __str__(self):
            return f'{self.firstname} {self.lastname}'
    
        def __repr__(self):
            return f'Person("{self.firstname}", "{self.lastname}")'
    
    person = Person('Joerg', 'Faschingbauer')
    
  • str() (and print())

    str(person)
    
    'Joerg Faschingbauer'
    
    print(person)
    
    Joerg Faschingbauer
    
  • repr() (and print() on lists)

    print(repr(person))
    
    Person("Joerg", "Faschingbauer")
    
    print([person])
    
    [Person("Joerg", "Faschingbauer")]