使用 isinstance 测试 Unicode 字符串

新手上路,请多包涵

我该怎么做:

 >>> s = u'hello'
>>> isinstance(s,str)
False

但我想 isinstance 返回 True 这个 Unicode 编码的字符串。是否有 Unicode 字符串对象类型?

原文由 A.D 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

测试 str

 isinstance(unicode_or_bytestring, str)

或者,如果您必须处理字节串,请分别测试 bytes

 isinstance(unicode_or_bytestring, bytes)

这两种类型是故意不可互换的; use explicit encoding (for str -> bytes ) and decoding ( bytes -> str ) to convert between the types.

In Python 2 , where the modern Python 3 str type is called unicode and str is the precursor of the Python 3 bytes type,您可以使用 basestring 来测试 两者

 isinstance(unicode_or_bytestring, basestring)

basestring 仅在 Python 2 中可用,并且是 strunicode 的抽象基类型。

如果你 只想 测试 unicode ,那么明确地这样做:

 isinstance(unicode_tring, unicode)

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 4.0 许可协议

是否有 Unicode 字符串对象类型?

是的,它叫做 unicode

 >>> s = u'hello'
>>> isinstance(s, unicode)
True
>>>

请注意,在 Python 3.x 中,此类型已被删除,因为 所有字符串现在都是 Unicode

原文由 user2555451 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题