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

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

提交回复
热议问题