【python基础】—python string和bytes类型互相转换(decode()/str()/encode()/bytes())


前言

去除str(bytes)输出的b字眼,比如将b’article.txt’ >> ‘article.txt’,将b’\xe5\x8f\x82\xe8\xae\xad\xe5\x90\x8d\xe5\x8d\x95.pdf’ >> ‘参训名单.pdf’。

bytes_text = b'article.txt'
str_text = 'article.txt'

print(type(bytes_text))
# 输出:
# <class 'bytes'>

print(type(str_text))
# 输出:
# <class 'str'>
byte_text = b'\xe5\x8f\x82\xe8\xae\xad\xe5\x90\x8d\xe5\x8d\x95.pdf'
str_text = '参训名单.pdf'

print(type(bytes_text))
# 输出:
# <class 'bytes'>

print(type(str_text))
# 输出:
# <class 'str'>

一、bytes转换成string两种方法

方法一:str(bytes,encoding=charset)

bytes_text = b'article.txt'
str(bytes_text,'utf-8')
# 输出:
# 'article.txt'

方法二:bytes.decode(charset)

bytes_text.decode('utf-8')
# 输出:
# 'article.txt'

二、string转成bytes两种方法

方法一:bytes(string,encoding=charset)

str_text='article.txt'
bytes(str_text,'utf-8')
# 输出:
# b'article.txt'

方法二:string.encode(charset)

str_text.encode('utf-8')
# 输出:
# b'article.txt'

三、string和bytes类型互相转换需要注意

如果报错:AttributeError: ‘bytes’ object has no attribute ‘encode’
或者报错:AttributeError: ‘str’ object has no attribute ‘decode’
请注意变量的类型,如果原本就是str,使用decode就会报错 AttributeError: ‘str’ object has no attribute ‘decode’,“字符”对象没有属性的解码的意思;同理,如果原本就是bytes,使用encode就会报错 AttributeError: ‘bytes‘ object has no attribute ‘encode‘,“字节”对象没有属性的编码的意思。

四、实际应用

获取邮件时解析邮件附件的名字,代码如下:

在这里插入图片描述

如果附件名称是全英文的

dh
# 输出:[(b'article.txt',us-ascii)]
dh[0][0] 
# 输出:b'article.txt'
dh[0][1] 
# 输出:us-ascii 
str(dh[0][0], dh[0][1]) 或者 dh[0][0].decode()
# 输出:article.txt

如果附件名称是中文的

dh
# [(b'=?UTF-8?B?5Y+C6K6t5ZCN5Y2VLnBkZg==?=', 'us-ascii')] 
dh[0][0] 
# 输出:b'=?UTF-8?B?5Y+C6K6t5ZCN5Y2VLnBkZg==?='
dh[0][1] 
# 输出:us-ascii 
filename_download,filename_charset = decode_header(str(dh[0][0], dh[0][1]))[0] # 如果附件的名字是中文,解码成功。

filename_download 
# 输出:b'\xe5\x8f\x82\xe8\xae\xad\xe5\x90\x8d\xe5\x8d\x95.pdf'
filename_charset 
# 输出:'utf-8'
filename_download.decode(filename_charset)
# 输出:'参训名单.pdf'

参考文章:
https://blog.csdn.net/PerfeyCui/article/details/108560650

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值