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

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

    You can get the class of an object by calling object.__class__, so in order to check if object is the default string type:

        isinstance(object,"".__class__)
    

    And You can place the following in the top of Your code so that strings enclosed by quotes are in unicode in python 2:

        from __future__ import unicode_literals
    
    0 讨论(0)
  • 2020-12-04 09:30

    You can try this at the beginning of your code:

    from __future__ import print_function
    import sys
    if sys.version[0] == "2":
        py3 = False
    else:
        py3 = True
    if py3: 
        basstring = str
    else:
        basstring = basestring
    

    and later in the code:

    anystring = "test"
    # anystring = 1
    if isinstance(anystring, basstring):
        print("This is a string")
    else:
        print("No string")
    
    0 讨论(0)
  • 2020-12-04 09:32

    If you're writing 2.x-and-3.x-compatible code, you'll probably want to use six:

    from six import string_types
    isinstance(s, string_types)
    
    0 讨论(0)
  • 2020-12-04 09:33

    The most terse approach I've found without relying on packages like six, is:

    try:
      basestring
    except NameError:
      basestring = str
    

    then, assuming you've been checking for strings in Python 2 in the most generic manner,

    isinstance(s, basestring)
    

    will now also work for Python 3+.

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