myString = 'éíěřáé'
我需要将这个字符串解码为 unicode。 下面的用法和这两种方法之间一般有什么区别吗?
myString.decode(encoding='UTF-8', errors='ignore')
和
unicode(myString, encoding='UTF-8', errors='ignore')
最佳答案
unicode
构造函数可以接受除字符串之外的其他类型:
>>> unicode(10)
u'10'
然而,对于 bytestring 的情况,这两种形式在很大程度上是等价的。某些编码选项对 unicode
构造函数无效,因为它们不会导致 unicode 输出,但对字节串的 .decode
方法有效,例如 '十六进制'
:
>>> unicode('10', encoding='hex')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: decoder did not return an unicode object (type=str)
关于python - string.decode() 与 unicode(string),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11861551/