How to find out if a Python object is a string?

前端 未结 14 1948
天涯浪人
天涯浪人 2020-11-30 17:47

How can I check if a Python object is a string (either regular or Unicode)?

相关标签:
14条回答
  • 2020-11-30 18:16

    Python 2

    Use isinstance(obj, basestring) for an object-to-test obj.

    Docs.

    0 讨论(0)
  • 2020-11-30 18:16

    In order to check if your variable is something you could go like:

    s='Hello World'
    if isinstance(s,str):
    #do something here,
    

    The output of isistance will give you a boolean True or False value so you can adjust accordingly. You can check the expected acronym of your value by initially using: type(s) This will return you type 'str' so you can use it in the isistance function.

    0 讨论(0)
  • 2020-11-30 18:17

    Python 2 and 3

    (cross-compatible)

    If you want to check with no regard for Python version (2.x vs 3.x), use six (PyPI) and its string_types attribute:

    import six
    
    if isinstance(obj, six.string_types):
        print('obj is a string!')
    

    Within six (a very light-weight single-file module), it's simply doing this:

    import sys
    PY3 = sys.version_info[0] == 3
    
    if PY3:
        string_types = str
    else:
        string_types = basestring
    
    0 讨论(0)
  • 2020-11-30 18:19

    For a nice duck-typing approach for string-likes that has the bonus of working with both Python 2.x and 3.x:

    def is_string(obj):
        try:
            obj + ''
            return True
        except TypeError:
            return False
    

    wisefish was close with the duck-typing before he switched to the isinstance approach, except that += has a different meaning for lists than + does.

    0 讨论(0)
  • 2020-11-30 18:19
    if type(varA) == str or type(varB) == str:
        print 'string involved'
    

    from EDX - online course MITx: 6.00.1x Introduction to Computer Science and Programming Using Python

    0 讨论(0)
  • 2020-11-30 18:20

    You can test it by concatenating with an empty string:

    def is_string(s):
      try:
        s += ''
      except:
        return False
      return True
    

    Edit:

    Correcting my answer after comments pointing out that this fails with lists

    def is_string(s):
      return isinstance(s, basestring)
    
    0 讨论(0)
提交回复
热议问题