Difference in python between basestring and types.StringType?

后端 未结 4 1363
一向
一向 2021-02-07 19:25

What\'s the difference between:

isinstance(foo, types.StringType)

and

isinstance(foo, basestring)

?

相关标签:
4条回答
  • 2021-02-07 19:48
    >>> import types
    >>> isinstance(u'ciao', types.StringType)
    False
    >>> isinstance(u'ciao', basestring)
    True
    >>> 
    

    Pretty important difference, it seems to me;-).

    0 讨论(0)
  • 2021-02-07 19:52

    For Python 2.x:

    try:
        basestring        # added in Python 2.3
    except NameError:
        basestring = (str, unicode)
    ...
    if isinstance(foo, basestring):
        ...
    

    Of course this might not work for Python 3, but I'm quite sure the 2to3 converter will take care of the topic.

    0 讨论(0)
  • 2021-02-07 19:55

    For Python2: basestring is the base class for both str and unicode, while types.StringType is str. If you want to check if something is a string, use basestring. If you want to check if something is a bytestring, use str and forget about types.

    0 讨论(0)
  • 2021-02-07 20:10

    This stuff is completely different in Python3

    types not longer has StringType
    str is always unicode
    basestring no longer exists

    So try not to sprinkle that stuff through your code too much if you might ever need to port it

    0 讨论(0)
提交回复
热议问题