The Python Oracle

What is the difference between isinstance('aaa', basestring) and isinstance('aaa', str)?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow

--

Chapters
00:00 What Is The Difference Between Isinstance('Aaa', Basestring) And Isinstance('Aaa', S
00:12 Answer 1 Score 9
00:26 Answer 2 Score 1
00:40 Answer 3 Score 4
01:01 Accepted Answer Score 404
02:07 Thank you

--

Full question
https://stackoverflow.com/questions/1979...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python2x #builtintypes

#avk47



ACCEPTED ANSWER

Score 404


In Python versions prior to 3.0 there are two kinds of strings "plain strings" and "unicode strings". Plain strings (str) cannot represent characters outside of the Latin alphabet (ignoring details of code pages for simplicity). Unicode strings (unicode) can represent characters from any alphabet including some fictional ones like Klingon.

So why have two kinds of strings, would it not be better to just have Unicode since that would cover all the cases? Well it is better to have only Unicode but Python was created before Unicode was the preferred method for representing strings. It takes time to transition the string type in a language with many users, in Python 3.0 it is finally the case that all strings are Unicode.

The inheritance hierarchy of Python strings pre-3.0 is:

          object
             |
             |
         basestring
            / \
           /   \
         str  unicode

'basestring' introduced in Python 2.3 can be thought of as a step in the direction of string unification as it can be used to check whether an object is an instance of str or unicode

>>> string1 = "I am a plain string"
>>> string2 = u"I am a unicode string"
>>> isinstance(string1, str)
True
>>> isinstance(string2, str)
False
>>> isinstance(string1, unicode)
False
>>> isinstance(string2, unicode)
True
>>> isinstance(string1, basestring)
True
>>> isinstance(string2, basestring)
True



ANSWER 2

Score 9


All strings are basestrings, but unicode strings are not of type str. Try this instead:

>>> a=u'aaaa'
>>> print isinstance(a, basestring)
True
>>> print isinstance(a, str)
False



ANSWER 3

Score 4


Really what you're asking is the difference between the basestring and str class.

Str is a class that inherits from basestr. But unicode strings also exist, as could other ones, if you wanted to make one.

>>> a = u'aaaa'
>>> isinstance(a, str)
False
>>> isinstance(a, basestring)
True



ANSWER 4

Score 1


Basestring is the superclass of string. In your example, a is of type "str" thus, it is both a basestring, and a str