Ben*_*Ben 0 python unicode python-2.7
我想知道在unicode字符串上调用str()时内部会发生什么.
# coding: utf-8
s2 = str(u'hello')
Run Code Online (Sandbox Code Playgroud)
s2只是str()arg的unicode字节表示吗?
它将尝试使用您的默认编码对其进行编码.在我的系统上,这是ASCII,如果有任何非ASCII字符,它将失败:
>>> str(u'?')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u3042' in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
请注意,如果您调用encode('ascii')它,则会出现同样的错误:
>>> u'?'.encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u3042' in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
正如您可能想象的那样,str处理一些参数并在其他参数上失败可以很容易地编写乍一看似乎有效的代码,但是一旦您在其中抛出一些国际字符就停止工作.Python 3通过明显地解决问题来避免这种情况:如果没有显式编码,您无法将Unicode转换为字节字符串:
>>> bytes(u'?')
TypeError: string argument without an encoding
Run Code Online (Sandbox Code Playgroud)