我有一個路徑變量的編碼問題,並將其插入到SQLite數據庫中。我試圖用編碼(「utf-8」)函數解決它,但沒有幫助。然後我使用unicode()函數,它給我類型unicode。在Python中使用unicode()和encode()函數
print type(path) # <type 'unicode'>
path = path.replace("one", "two") # <type 'str'>
path = path.encode("utf-8") # <type 'str'> strange
path = unicode(path) # <type 'unicode'>
最後我獲得了的unicode類型,但我仍然有其存在時路徑變量的類型是海峽同樣的錯誤
sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings.
你能幫我解決這個錯誤並解釋encode("utf-8")
和unicode()
函數的正確用法?我經常與之戰鬥。
編輯:
這的execute()陳述引發的錯誤:
cur.execute("update docs set path = :fullFilePath where path = :path", locals())
我忘了改fullFilePath變量,同樣的問題受到影響的編碼,但我現在很困惑。我應該只使用unicode()或編碼(「utf-8」)或兩者嗎?
我不能使用
fullFilePath = unicode(fullFilePath.encode("utf-8"))
,因爲它提出了這樣的錯誤:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 32: ordinal not in range(128)
的Python版本是2.7.2
哪裏是引發錯誤的代碼? – newtover 2012-04-23 20:48:04
您確切的問題已經得到解答:[http://stackoverflow.com/questions/2392732/sqlite-python-unicode-and-non-utf-data][1] [1]:http:// stackoverflow.com/questions/2392732/sqlite-python-unicode-and-non-utf-data – garnertb 2012-04-23 20:51:25
@newtover我編輯了這個問題。 – xralf 2012-04-23 20:55:58