当提供三个参数时,`str()`方法返回什么?

时间:2013-06-12 09:53:46

标签: python string

The fine manual没有说明str()方法在提供三个参数时所执行的操作,正如我在requests/models.py的代码中找到的那样:

content = str(self.content, encoding, errors='replace') 

这在哪里记录?它做了什么?

3 个答案:

答案 0 :(得分:7)

这不是内置的str功能。看看imports at the top

from .compat import (
    cookielib, urlparse, urlunparse, urlsplit, urlencode, str, bytes, StringIO,
    is_py2, chardet, json, builtin_str, basestring)

Kenneth为Python 2和3之间的兼容性定义了自己的compat模块,并且他覆盖了几个内置函数,包括str

作为you can see in that module,在Python 2中,它将unicode别名为str,因此它与Python3 str几乎相同。

答案 1 :(得分:3)

您正在阅读第2版的文档,但使用(或匹配)Python 3查看代码。

The docs for version 3说:

str(object='')
str(object=b'', encoding='utf-8', errors='strict')
     

返回str版本的对象。有关详细信息,请参阅str()。

在链接后面会说明encodingerrors个关键字参数:

  

如果至少提供了encodingerrors中的一个,object应该是类似bytes的对象(例如bytesbytearray })。在这种情况下,如果objectbytes(或bytearray)对象,则str(bytes, encoding, errors)相当于bytes.decode(encoding, errors)。否则,在调用bytes之前获取buffer对象底层的bytes.decode()对象。

答案 2 :(得分:1)

在这里添加daniel-roseman的答案是documentation and what does it do.。由于所述代码中的str代表unicode

相关问题