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

后端 未结 10 2342
有刺的猬
有刺的猬 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: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.

提交回复
热议问题