1. 程式人生 > >Python decode和encody

Python decode和encody

s = "我今天非常的困"
bs = s.encode("utf-8")# 把字串轉化成utf-8格式bytes
# bytes 不是給人看的, 給機器用的
# 21個位元組
b'\xe6\x88\x91\xe4\xbb\x8a\xe5\xa4\xa9\xe9\x9d\x9e\xe5\xb8\xb8\xe7\x9a\x84\xe5\x9b\xb0'
bs = s.encode("gbk")
# 14個位元組
b'\xce\xd2\xbd\xf1\xcc\xec\xb7\xc7\xb3\xa3\xb5\xc4\xc0\xa7'
print(bs)

# utf-8和gbk是不能直接轉換的, 必須使用unicode來轉換

bs = b'\xce\xd2\xbd\xf1\xcc\xec\xb7\xc7\xb3\xa3\xb5\xc4\xc0\xa7'
# 把位元組轉化回字符串
s = bs.decode("gbk")
print(s)

bs = b'\xe6\x88\x91\xe4\xbb\x8a\xe5\xa4\xa9\xe9\x9d\x9e\xe5\xb8\xb8\xe7\x9a\x84\xe5\x9b\xb0'
# # 把這個bytes轉化成gbk的bytes
s = bs.decode("utf-8")
g = s.encode("gbk")
print(g)

# 關於bytes,非ascii中的內容,展示的時候都是\x..如果是ascii中的內容,原樣輸出
name = "alex昨天吃多了"
bs = name.encode("gbk") # b'alex\xd7\xf2\xcc\xec\xb3\xd4\xb6\xe0\xc1\xcb'
print(bs)

bss = name.encode("utf-8") # b'alex\xe6\x98\xa8\xe5\xa4\xa9\xe5\x90\x83\xe5\xa4\x9a\xe4\xba\x86'
print(bss)