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

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

    If one wants to stay away from explicit type-checking (and there are good reasons to stay away from it), probably the safest part of the string protocol to check is:

    str(maybe_string) == maybe_string
    

    It won't iterate through an iterable or iterator, it won't call a list-of-strings a string and it correctly detects a stringlike as a string.

    Of course there are drawbacks. For example, str(maybe_string) may be a heavy calculation. As so often, the answer is it depends.

    EDIT: As @Tcll points out in the comments, the question actually asks for a way to detect both unicode strings and bytestrings. On Python 2 this answer will fail with an exception for unicode strings that contain non-ASCII characters, and on Python 3 it will return False for all bytestrings.

提交回复
热议问题