Python encode()方法根据提供的编码标准对字符串进行编码。默认情况下,Python字符串采用unicode格式,但也可以编码为其他标准。
编码是将文本从一种标准代码转换为另一种标准代码的过程。
encode(encoding="utf-8", errors="strict")
两者都是可选的。默认编码为UTF-8。
它返回一个编码的字符串。
一种将unicode字符串编码为utf-8编码标准的简单方法。
# Python encode() function example # 变量声明 str = "HELLO" encode = str.encode() # 显示结果 print("Old value", str) print("Encoded value", encode)
输出:
Old value HELLO Encoded value b 'HELLO'
无涯教程正在编码一个拉丁字符
? into default encoding. # Python encode() function example # 变量声明 str = "HËLLO" encode = str.encode() # 显示结果 print("Old value", str) print("Encoded value", encode)
输出:
Old value HËLLO Encoded value b'H\xc3\x8bLLO'
正在将拉丁字符编码为ascii,它会引发错误。参见下面的例子
链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-string-encode-method.html
来源:LearnFk无涯教程网
# Python encode() function example # 变量声明 str = "HËLLO" encode = str.encode("ascii") # 显示结果 print("Old value", str) print("Encoded value", encode)
输出:
UnicodeEncodeError: 'ascii' codec can't encode character '\xcb' in position 1: ordinal not in range(128)
如果无涯教程想忽略错误,则将ignore作为第二个参数传递。
# Python encode() function example # 变量声明 str = "HËLLO" encode = str.encode("ascii","ignore") # 显示结果 print("Old value", str) print("Encoded value", encode)
输出:
Old value HËLLO Encoded value b'HLLO'
它忽略错误并用?替换字符。标记。
# Python encode() function example # 变量声明 str = "HËLLO" encode = str.encode("ascii","replace") # 显示结果 print("Old value", str) print("Encoded value", encode)
输出:
Old value HËLLO Encoded value b'H?LLO'
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)