Python中的encode()和decode()方法详解
发布时间:2023-12-18 03:57:20
在Python中,字符串对象都有一个encode()和decode()方法用于编码和解码字符串。
1. encode()方法:
- encode()方法用于将字符串编码成指定的字符编码格式。它接受一个参数,指定要使用的字符编码格式,默认为UTF-8。
- 使用例子:
# 使用默认的UTF-8编码格式将字符串编码
s = "你好"
encoded_s = s.encode()
print(encoded_s) # b'\xe4\xbd\xa0\xe5\xa5\xbd'
# 使用指定的字符编码格式将字符串编码
s = "你好"
encoded_s = s.encode("gbk")
print(encoded_s) # b'\xc4\xe3\xba\xc3'
- 在 个例子中,使用默认的UTF-8编码格式将字符串"你好"编码成字节串b'\xe4\xbd\xa0\xe5\xa5\xbd'。
- 在第二个例子中,使用指定的gbk编码格式将字符串"你好"编码成字节串b'\xc4\xe3\xba\xc3'。
2. decode()方法:
- decode()方法用于将已编码的字节串解码成字符串。它接受一个参数,指定要使用的字符编码格式,默认为UTF-8。
- 使用例子:
# 使用默认的UTF-8编码格式将字节串解码成字符串
encoded_s = b'\xe4\xbd\xa0\xe5\xa5\xbd'
decoded_s = encoded_s.decode()
print(decoded_s) # 你好
# 使用指定的字符编码格式将字节串解码成字符串
encoded_s = b'\xc4\xe3\xba\xc3'
decoded_s = encoded_s.decode("gbk")
print(decoded_s) # 你好
- 在 个例子中,使用默认的UTF-8编码格式将字节串b'\xe4\xbd\xa0\xe5\xa5\xbd'解码成字符串"你好"。
- 在第二个例子中,使用指定的gbk编码格式将字节串b'\xc4\xe3\xba\xc3'解码成字符串"你好"。
需要注意的是,使用encode()和decode()方法时,要确保编码和解码使用的字符编码格式是一致的,否则可能会导致出错。
