字符串和字节之间的转换(含有中文的不能使用ascii编码转,Python会报错),加上errors参数可以忽略错误,正常转换其他可以转换的
-
字符串转字节
# 输出结果:b\'string to bytes\' print(\"string to bytes\".encode(\"utf-8\")) # 输出结果:b\'string to bytes\' print(\"string to bytes\".encode(\"ascii\")) # 输出结果:b\'\\xe5\\xad\\x97\\xe7\\xac\\xa6\\xe4\\xb8\\xb2\\xe8\\xbd\\xac\\xe5\\xad\\x97\\xe8\\x8a\\x82\' print(\"字符串转字节\".encode(\"utf-8\")) # 输出结果:报错 print(\"字符串转字节\".encode(\"ascii\")) # 输出结果:b\'\' print(\"字符串转字节\".encode(\"ascii\",errors=\'ignore\')) -
字节转字符串
# 输出结果:string to bytes print(b\'string to bytes\'.decode(\"utf-8\")) # 输出结果:string to bytes print(b\'string to bytes\'.decode(\"ascii\")) # 输出结果:字符串转字节 print(b\'\\xe5\\xad\\x97\\xe7\\xac\\xa6\\xe4\\xb8\\xb2\\xe8\\xbd\\xac\\xe5\\xad\\x97\\xe8\\x8a\\x82\'.decode(\"utf-8\")) # 输出结果:报错 print(b\'\\xe5\\xad\\x97\\xe7\\xac\\xa6\\xe4\\xb8\\xb2\\xe8\\xbd\\xac\\xe5\\xad\\x97\\xe8\\x8a\\x82\'.decode(\"ascii\")) # 输出结果:空字符串 \'\' print(b\'\\xe5\\xad\\x97\\xe7\\xac\\xa6\\xe4\\xb8\\xb2\\xe8\\xbd\\xac\\xe5\\xad\\x97\\xe8\\x8a\\x82\'.decode(\"ascii\",errors=\'ignore\')) -
len方法使用:len()函数计算的是str的字符数,如果换成bytes,len()函数就计算字节数
# 输出结果:2 print(len(\'中文\')) # 输出结果:6 print(len(\'中文\'.encode(\"utf-8\")))
继续阅读与本文标签相同的文章
下一篇 :
手工米成本仅7美元,8年斩获3500倍利润!
-
打通“最后一公里”送药地图 访海派医药集团总经理张翔
2026-05-18栏目: 教程
-
上海首个保税展示展销场所亮相 海外商品“全球同质同价”
2026-05-18栏目: 教程
-
微信聊天记录导出excel使用方法分享卓师兄微信恢复大师
2026-05-18栏目: 教程
-
用好SmartArt,快速制作美观工整的PPT
2026-05-18栏目: 教程
-
CMU 15-721 15-查询执行和处理过程 Query Execution & Processing
2026-05-18栏目: 教程
