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

文章目录

  • 前言
  • 一、bytes转换成string两种方法
  • 二、string转成bytes两种方法
  • 三、string和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))
# 输出:
# 

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

print(type(bytes_text))
# 输出:
# 

print(type(str_text))
# 输出:
# 

一、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‘,“字节”对象没有属性的编码的意思。

四、实际应用

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

【python基础】—python string和bytes类型互相转换(decode()/str()/encode()/bytes())_第1张图片

如果附件名称是全英文的

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

你可能感兴趣的:(python基础,python,开发语言)