python3中默認編碼方式為utf-8。在存儲和顯示上,python3使用文本字符和二進制數(shù)據(jù)進行區(qū)分,更加明確和清晰。
默認情況下,Python 3 源碼文件以 UTF-8 編碼,所有字符串都是 unicode 字符串。(推薦學習:Python視頻教程)
當然你也可以為源碼文件指定不同的編碼:
# -*- coding: cp-1252 -*-
文本字符使用str類型表示,str 能表示 Unicode 字符集中所有字符,而二進制數(shù)據(jù)使用bytes類型表示。
str與bytes之間的轉換
# bytes object b = b"example" # str object s = "example" # str to bytes bytes(s, encoding = "utf8") # bytes to str str(b, encoding = "utf-8")
默認使用utf-8
# bytes object b = b"example" # str object s = "example" # an alternative method # str to bytes str.encode(s) # bytes to str bytes.decode(b)