Python中字符串和字节串怎么转换
在Python中,字符串和字节串可以通过encode()和decode()方法相互转换。
- 将字符串转换为字节串:
s = "Hello"
b = s.encode() # 使用默认编码(utf-8)转换为字节串
print(b) # b'Hello'
# 可以指定其他编码方式
b = s.encode("utf-16")
print(b) # b'\xff\xfeH\x00e\x00l\x00l\x00o\x00'
- 将字节串转换为字符串:
b = b'Hello'
s = b.decode() # 使用默认编码(utf-8)转换为字符串
print(s) # Hello
# 可以指定其他编码方式
s = b.decode("utf-16")
print(s) # Hello