Python编码解码技巧汇总

Python编码解码技巧汇总

encode

encode将字符串转换为bytes类型的对象 (即b为前缀, bytes类型), 即Ascll编码, 字节数组

a = "检测到网站攻击"
print(a.encode())
print(type(a.encode()))

# b'xe6xa3x80xe6xb5x8bxe5x88xb0xe7xbdx91xe7xabx99xe6x94xbbxe5x87xbb'
# <class 'bytes'>

decode

decode将字节转换为字符串

bytes_str = b'xe6xa3x80xe6xb5x8bxe5x88xb0xe7xbdx91xe7xabx99xe6x94xbbxe5x87xbb'
print(bytes_str.decode())
print(type(bytes_str.decode()))

# 检测到网站攻击
# <class 'str'>

encode('raw_unicode_escape')和 decode('raw_unicode_escape')

重要

某字符串的内容为bytes形式,例如:

a = 'xe6xa3x80xe6xb5x8bxe5x88xb0xe7xbdx91xe7xabx99xe6x94xbbxe5x87xbb'

可使用 encode('raw_unicode_escape') 将此str转化为bytes, 再decode为str

a = 'xe6xa3x80xe6xb5x8bxe5x88xb0xe7xbdx91xe7xabx99xe6x94xbbxe5x87xbb'

bytes_str = a.encode('raw_unicode_escape')

print(bytes_str.decode())

# 检测到网站攻击

可使用decode('raw_unicode_escape')输出内容为bytes形式的字符串

a = b'xe6xa3x80xe6xb5x8bxe5x88xb0xe7xbdx91xe7xabx99xe6x94xbbxe5x87xbb'
print(a.decode('raw_unicode_escape'))

# xe6xa3x80xe6xb5x8bxe5x88xb0xe7xbdx91xe7xabx99xe6x94xbbxe5x87xbb
抟扶摇而上者九万里
原文地址:https://www.cnblogs.com/fengting0913/p/14615908.html