Python str() Function

Python str() function is one of the built-in functions. This function returns the string representation of the object. If there is no argument provided, it returns an empty string.

Python str() Function Examples

Let’s look at some simple examples of the str() function.

>>> str("AskPython")
'AskPython'
>>> str(10)
'10'
>>> str(None)
'None'
>>> str()
''
>>> 

How to implement str() function for an Object

When we call the str() function with an object argument, it calls the __str__() function of the object. So, we can implement the __str__() function for the object, which should return a string.

First, let’s see what happens when we don’t implement the __str__() function for an object.

class Emp:

    id = 0
    name = ''

    def __init__(self, i, n):
        self.id = i
        self.name = n


d1 = Emp(10, 'Pankaj')

print(str(d1))

When we run above code, it prints:

<main.Emp object at 0x104e72ee0>

What’s this?

When __str__() function is not implemented, the str() function fallbacks to repr() function. The object class provides repr() function implementation, which returns the memory address of the object.

This output doesn’t help us because as a developer, there is no useful information about the object. Let’s implement the __str__() function.

def __str__(self):
    return f'Emp::ID={self.id}, Name={self.name}'

Output:

Python Str Function
Python Str Function

Summary

  • The python str() function is one of the built-in functions.
  • The str() function internally calls __str__() function, in absence it fallbacks to repr() function.
  • If there is no argument provided, the str() function returns an empty string.
  • We can use the str() function to convert object to string. It’s useful when you want to convert numbers to strings, etc.
  • It’s a good idea to implement the __str__() function for data objects, it helps in getting useful information about the object easily.

What’s Next?

Resources