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

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

    Python 2

    To check if an object o is a string type of a subclass of a string type:

    isinstance(o, basestring)
    

    because both str and unicode are subclasses of basestring.

    To check if the type of o is exactly str:

    type(o) is str
    

    To check if o is an instance of str or any subclass of str:

    isinstance(o, str)
    

    The above also work for Unicode strings if you replace str with unicode.

    However, you may not need to do explicit type checking at all. "Duck typing" may fit your needs. See http://docs.python.org/glossary.html#term-duck-typing.

    See also What’s the canonical way to check for type in python?

提交回复
热议问题