Are there any cases where str()
throws an exception in Python?
The str() function converts values to a string form so they can be combined with other strings. The "print" function normally prints out one or more python items followed by a newline.
The STR() function returns a number as a string.
Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.
str is a built-in function (actually a class) which converts its argument to a string. string is a module which provides common string operations. Put another way, str objects are a textual representation of some object o , often created by calling str(o) . These objects have certain methods defined on them.
Yes, it can fail for custom classes:
>>> class C(object):
... def __str__(self):
... return 'oops: ' + oops
...
>>> c = C()
>>> str(c)
NameError: global name 'oops' is not defined
It can even fail for some of the built-in classes, such as unicode
:
>>> u = u'\xff'
>>> s = str(u)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0:
ordinal not in range(128)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With