共計 348 個字符,預計需要花費 1 分鐘才能閱讀完成。
在 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
丸趣 TV 網 – 提供最優質的資源集合!
正文完