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

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

提交回复
热议问题