[英]What does str.encode expect as input?
我希望在我的項目中為所有字符串使用unicode
而不是str
。 我正在嘗試使用str.encode
方法,但無法從文檔中看出encode
方法完全或期望作為輸入的內容。
希臘小寫字母pi是U + 03C0,當以UTF-8編碼時是0xCF 0x80。 我得到以下內容:
>>> s1 = '\xcf\x80'
>>> s1.encode('utf-8','ignore')
Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
s1.encode('utf-8','ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcf in position 0: ordinal not in range(128)
我嘗試過:
>>> s2='\x03\xc0'
>>> s2.encode('utf-8','ignore')
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
s2.encode('utf-8','ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc0 in position 1: ordinal not in range(128)
encode
期望什么作為輸入,為什么'ignore'選項不會忽略錯誤? 我試過'替換',這也沒有掩蓋錯誤。
在Python 2.x中, str
是一個字節字符串(已編碼)。 您可以將其解碼為unicode對象:
>>> s1 = '\xcf\x80' # string literal (str)
>>> s1.decode('utf-8')
u'\u03c0'
對於unicode對象,您可以執行編碼:
>>> u1 = u'\u03c0' # unicode literal (unicode) U+03C0
>>> u1.encode('utf-8')
'\xcf\x80'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.