python
字符串
编码
说明
《Python 教程》 帮助读者成为泛程序员,持续修订中,提供建议、纠错、催更加微信 sin80c。查看 更新日志。作者开办 Python 数据分析培训,详情 Python 数据分析培训。
![]() |
本教程作者所著新书《深入浅出Pandas:利用Python进行数据处理与分析》(ISBN:9787111685456)已由机械工业出版社出版上市,各大电商平台有售,欢迎:查看详情并关注购买。 |
Python 的字符串方法 encode() 方法返回给定字符串的编码版本,编码为字节串。
示例如下:
'123'.encode()
# b'123'
'hello'.encode()
# b'hello'
'pythön!'.encode()
# b'pyth\xc3\xb6n!'
参数示例:
txt = "My name is Ståle"
print(txt.encode(encoding="ascii",errors="backslashreplace"))
print(txt.encode(encoding="ascii",errors="ignore"))
print(txt.encode(encoding="ascii",errors="namereplace"))
print(txt.encode(encoding="ascii",errors="replace"))
print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))
'''
b'My name is St\\xe5le'
b'My name is Stle'
b'My name is St\\N{LATIN SMALL LETTER A WITH RING ABOVE}le'
b'My name is St?le'
b'My name is Ståle'
'''
语法如下:
string.encode(encoding='UTF-8',errors='strict')
默认情况下,encode() 方法不需要任何参数。它返回字符串的utf-8编码版本。如果失败,它将引发UnicodeDecodeError异常。
它有两个参数:
从 Python 3.0 开始,字符串存储为 Unicode,即字符串中的每个字符都由代码点表示。因此,每个字符串只是一系列 Unicode 代码点。
为了有效存储这些字符串,代码点序列被转换为一组字节。这个过程称为编码。
存在各种不同的编码,它们对字符串的处理方式不同。流行的编码是 utf-8、ascii 等。
使用 string encode() 方法,可以将 unicode 字符串转换为 Python 支持的任何编码。默认情况下,Python使用 utf-8 编码。