Sunday 11 July 2021

What differences are between `format()` and `str()`?

>>> format(sys.stdout)
"<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>"
>>> str(sys.stdout)
"<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>"

I am not very sure about the following quotes from Python library references. What differences are between format() and str(), or between object.__format__(self, format_spec) and object.__str__(self )? When shall we use which?

object.__str__(self )

Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object.

object.__format__(self, format_spec)

Called by the format() built-in function, and by extension, evaluation of formatted string literals and the str.format() method, to produce a “formatted” string representation of an object.



from What differences are between `format()` and `str()`?

No comments:

Post a Comment