-1

What are the differences between the __str__() and str() methods in python?

SherylHohman
  • 14,460
  • 16
  • 79
  • 88

2 Answers2

2

__str__ (usually read dunder, for double under) is an instance method that is called whenever you run str(<object>) and returns the string representation of the object.

str(foo) acts as a function trying to convert foo into a string.

Note:
There is also a __repr__() method which is fairly similar to __str__(), the main difference being __repr__ should return an unambiguous string and __str__ is for a readable string. For a great response on the diffences between the two I'd suggest giving this answer a read.

WillMonge
  • 985
  • 10
  • 19
0

__str__() is a magic instance method that doee this: when you print a class instance variable with print(), it will give you a string that can be modified by changing the returned string in the __str__() method. There's probably a better explanation to it but I can show you with code:

class Thing:
    def __init__(self):
        pass
    def __str__(self):
       return "What do you want?"  #always use return

a = Thing()
print(a)

OUTPUT:

What do you want?

str() just converts a variable into a string type variable.

print(str(12.0))

OUTPUT:

'12.0'

You can confirm it is a string using the type() function.

print(type(str(12.)))

I don't know the exact output of that but it will peobably have 'str' in it.

WillMonge
  • 985
  • 10
  • 19
Ethanol
  • 360
  • 4
  • 18