How to check if variable is string with python 2 and 3 compatibility

后端 未结 10 2292
有刺的猬
有刺的猬 2020-12-04 08:47

I\'m aware that I can use: isinstance(x, str) in python-3.x but I need to check if something is a string in python-2.x as well. Will isinstance(x, str)

相关标签:
10条回答
  • 2020-12-04 09:14

    The future library adds (to Python 2) compatible names, so you can continue writing Python 3. You can simple do the following:

    from builtins import str
    isinstance(x, str) 
    

    To install it, just execute pip install future.

    As a caveat, it only support python>=2.6,>=3.3, but it is more modern than six, which is only recommended if using python 2.5

    0 讨论(0)
  • 2020-12-04 09:16

    Be careful! In python 2, str and bytes are essentially the same. This can cause a bug if you are trying to distinguish between the two.

    >>> size = 5    
    >>> byte_arr = bytes(size)
    >>> isinstance(byte_arr, bytes)
    True
    >>> isinstance(byte_arr, str)
    True
    
    0 讨论(0)
  • 2020-12-04 09:20

    Maybe use a workaround like

    def isstr(s):
        try:
            return isinstance(s, basestring)
        except NameError:
            return isinstance(s, str)
    
    0 讨论(0)
  • 2020-12-04 09:28

    This is @Lev Levitsky's answer, re-written a bit.

    try:
        isinstance("", basestring)
        def isstr(s):
            return isinstance(s, basestring)
    except NameError:
        def isstr(s):
            return isinstance(s, str)
    

    The try/except test is done once, and then defines a function that always works and is as fast as possible.

    EDIT: Actually, we don't even need to call isinstance(); we just need to evaluate basestring and see if we get a NameError:

    try:
        basestring  # attempt to evaluate basestring
        def isstr(s):
            return isinstance(s, basestring)
    except NameError:
        def isstr(s):
            return isinstance(s, str)
    

    I think it is easier to follow with the call to isinstance(), though.

    0 讨论(0)
  • 2020-12-04 09:29

    What about this, works in all cases?

    isinstance(x, ("".__class__, u"".__class__))
    
    0 讨论(0)
  • 2020-12-04 09:29

    type(string) == str

    returns true if its a string, and false if not

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