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

前端 未结 14 2017
天涯浪人
天涯浪人 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: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
    

提交回复
热议问题