Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can str() fail in Python?

Tags:

python

Are there any cases where str() throws an exception in Python?

like image 873
Brendan Long Avatar asked Feb 01 '11 00:02

Brendan Long


People also ask

What does str () function do 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.

What does str () return?

The STR() function returns a number as a string.

What does STR return in Python?

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.

What is the difference between STR and string in Python?

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.


1 Answers

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)
like image 73
Mark Byers Avatar answered Sep 28 '22 07:09

Mark Byers