欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python3 bytes和str转换,解决图片base64调用api的问题

发布时间:2025/3/21 python 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python3 bytes和str转换,解决图片base64调用api的问题 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

bytes 转换为 str

str(b, encoding = "utf-8")  

str(b, encoding = "gbk")  

encoding中写的是原来byte变量的编码  什么类型的编码的字节就要转换成什么类型的编码的字符串

通过

import chardet ret = chardet.detect(变量)

可以查看原有变量的编码类型enncoding

或者通过decode解码,但是可能会出错。推荐如上

string=b.decode() # 第一参数默认utf8,第二参数默认strict print(string) string=b.decode('utf-8','ignore') # 忽略非法字符,用strict会抛出异常 print(string) string=b.decode('utf-8','replace') # 用?取代非法字符 print(string)

str 转换为 bytes

b=bytes(str1, encoding='utf-8') print(b) b=str1.encode('utf-8') print(b)

str没有decode方法,如果调用str.decode会报错

AttributeError: 'str' object has no attribute 'decode'


写爬虫时候,返回的response里中文乱码,根据原页面的<meta charset="gb2312">

来修改编码为

response.encoding = 'gb2312'

总结

以上是生活随笔为你收集整理的python3 bytes和str转换,解决图片base64调用api的问题的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。