如何检查Python对象是否为字符串(常规或Unicode)?


当前回答

if type(varA) == str or type(varB) == str:
    print 'string involved'

从 EDX -在线课程 MITx: 6.00.1x使用Python的计算机科学和编程介绍

其他回答

Python 3

在Python 3中。x basestring不再可用,因为str是唯一的字符串类型(与Python 2的语义相同)。x的unicode)。

Python 3中的检查。X就是:

isinstance(obj_to_test, str)

这遵循了官方2to3转换工具的修复:将basestring转换为str。

我可能会像其他人提到的那样,用鸭子类型来处理这个问题。我怎么知道一个字符串真的是一个字符串?显然是通过将其转换为字符串!

def myfunc(word):
    word = unicode(word)
    ...

如果arg已经是一个字符串或unicode类型,real_word将保持其值不变。如果传递的对象实现了__unicode__方法,则该方法用于获取其unicode表示。如果传递的对象不能作为字符串使用,unicode内置将引发异常。

你可以通过连接一个空字符串来测试它:

def is_string(s):
  try:
    s += ''
  except:
    return False
  return True

编辑:

更正我的回答后的评论指出,这失败与列表

def is_string(s):
  return isinstance(s, basestring)
if type(varA) == str or type(varB) == str:
    print 'string involved'

从 EDX -在线课程 MITx: 6.00.1x使用Python的计算机科学和编程介绍

Python 2

对于测试对象obj,使用isinstance(obj, basestring)。

文档。