Python str()函数
Python str()函数返回对象的字符串版本。
Syntax: str(object, encoding=’utf-8?, errors=’strict’)
Parameters:
- object: The object whose string representation is to be returned.
- encoding: Encoding of the given object.
- errors: Response when decoding fails.
Returns: String version of the given object
Python str()函数示例
示例 1: str()函数的演示
Python3
# Python program to demonstrate
# strings
# Empty string
s = str()
print(s)
# String with values
s = str("GFG")
print(s)
Python3
# Python program to demonstrate
# strings
num = 100
s = str(num)
print(s, type(s))
num = 100.1
s = str(num)
print(s, type(s))
Python3
# Python program to demonstrate
# str()
a = bytes("ŽString", encoding = 'utf-8')
s = str(a, encoding = "ascii", errors ="ignore")
print(s)
输出:
GFG
示例 2:转换为字符串
Python3
# Python program to demonstrate
# strings
num = 100
s = str(num)
print(s, type(s))
num = 100.1
s = str(num)
print(s, type(s))
输出:
100
100.1
字符串中的错误
这个函数有六种类型的错误。
- 严格(默认):它会引发 UnicodeDecodeError。
- 忽略:它忽略不可编码的 Unicode
- replace:它用问号替换不可编码的 Unicode
- xmlcharrefreplace:它插入 XML字符引用而不是不可编码的 Unicode
- 反斜杠替换:插入 \uNNNN Espace 序列而不是不可编码的 Unicode
- namereplace:插入 \N{...} 转义序列而不是不可编码的 Unicode
例子:
Python3
# Python program to demonstrate
# str()
a = bytes("ŽString", encoding = 'utf-8')
s = str(a, encoding = "ascii", errors ="ignore")
print(s)
输出:
String
在上面的例子中,字符Ž应该引发错误,因为它不能被 ASCII 解码。但它被忽略了,因为错误被设置为ignore 。