str() 语法
str()
的语法是
str(object, encoding='utf-8', errors='strict')
在这里,encoding 和 errors 参数仅用于 object 类型为 bytes 或 bytearray 时。
str() 参数
str()
方法接受三个参数
- object - 要返回其字符串表示形式的对象
- encoding - 给定字节对象需要解码为的编码(可以是 UTF-8, ASCII 等)
- errors - 解码失败时的响应(可以是 strict, ignore, replace 等)
注意:错误类型有六种:strict, ignore, replace, xmlcharrefreplace, namereplace, backslashreplace。默认错误是 strict。
str() 返回值
str()
方法返回
- 给定 object 的可打印字符串表示形式
- 给定 byte object 在提供的 encoding 中的字符串表示形式
示例 1:Python() 字符串
# string representation of Luke
name = str('Luke')
print(name)
# string representation of an integer 40
age = str(40)
print(age)
# string representation of a numeric string 7ft
height = str('7ft')
print(height)
输出
Luke 40 7ft
在上面的示例中,我们使用了 str()
方法,并传入了不同类型的参数,如字符串、整数和数字字符串。
示例 2:带字节对象的 str()
我们可以将 str()
方法与 字节对象 一起使用,字节对象由 bytes() 方法定义。
在这种情况下,我们需要指定要将字节对象转换成的编码以及 str()
方法可以执行的错误检查类型。
# declare a byte object
b = bytes('pythön', encoding='utf-8')
# convert a utf-8 byte object to ascii with errors ignored
print(str(b, encoding='ascii', errors='ignore'))
# convert a utf-8 byte object to ascii with strict error
print(str(b, encoding='ascii', errors='strict'))
输出
pythn UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)
在第一个示例中,我们创建了一个字节对象 b,其字符串为 'pythön'
,编码为 utf-8
。
我们将 b 对象传递给 str()
方法,并将编码指定为 ascii
。
在这里,我们将 errors
参数设置为 ignore
,因此 str()
方法会忽略字符 'ö'
。由于该方法无法将此字符解码为 ascii
,我们得到了输出 pythn。
类似地,在第二个示例中,我们将错误设置为 strict
。在这种情况下,str()
方法会考虑字符 'ö'
并产生 UnicodeDecodeError 作为输出。
另请阅读