Python encoding and decoding

Python encoding and decoding

encoding and decoding

encode 和 decode 编码和解码文本数据,在python中可以用 str.encode() 把字符串编码为bytes 和 bytes.decode() 把bytes解码为字符串 方法来进行编码和解码操作,括号内指定编码格式。

encode 和 decode 编码和解码文本数据,在python中可以用 字符串.encode() 和 bytes格式数据.decode() 方法来进行编码和解码操作,括号内指定格式。

# 如 'abc'.encode() 把字符串 abc 编码
# 如 b'abc'.decode() 把bytes格式的 abc 解码

example

text = "Hello, World!"

# Encode the text to bytes using UTF-8 encoding
encoded_text = text.encode("utf-8")

# Decode the bytes to a stringd
decoded_text = encoded_text.decode("utf-8")

print(encoded_text)
# 最前面的 b,表示格式为 bytes,即编码为bytes格式
# b'Hello, World!'

print(decoded_text)
# 'Hello, World!'

# 此外,还有其他库如 base64 也可用于编码和解码文本数据

k = 'abc'
m = 'bbb'
a = hmac.new(k.encode('utf-8'),m.encode('utf-8'),'SHA256').hexdigest()  # 把 k 和 m 编码为bytes,再用SHA256算法加密,用hexdigest()方法,返回十六进制哈希值
print(a)
# 80491b7b7159a14f0bcdd5bd1bb8209f307ab055bc9fff173d6b9608434b4555


kk = b'abc'
mm = b'bbb'
aa = hmac.new(kk,mm,'SHA256').hexdigest()   # 把bytes格式的 kk 和 mm,用SHA256算法加密,用hexdigest()方法,返回十六进制哈希值
print(aa)
# 80491b7b7159a14f0bcdd5bd1bb8209f307ab055bc9fff173d6b9608434b4555

Guess you like

Origin blog.csdn.net/qq_44659804/article/details/128819607