我有一個用UTF-8編碼寫入一些字符串的Python腳本。在我的腳本中,我主要使用str()
函數來轉換爲字符串。它看起來像這樣:瞭解Python Unicode和Linux終端
mystring="this is unicode string:"+japanesevalues[1]
#japanesevalues is a list of unicode values, I am sure it is unicode
print mystring
我不使用Python終端,只是標準的Linux紅帽x86_64終端。我設置終端輸出utf8字符。
如果我執行此:
#python myscript.py
this is unicode string: カラダーズ ソフィー
但如果我這樣做:
#python myscript.py > output
我得到了典型的錯誤:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 253-254: ordinal not in range(128)
這是爲什麼?
在你的問題,你說的「某些字符串使用UTF-8編碼」你怎麼能確保該字符串用UTF-8編碼,你做了什麼? –
@ venus.w對不起,我幫不了你。我正在讀取以UTF-8編碼的數據庫和CSV中的字符串,但我只是假設編碼實際上是UTF-8(因爲如果我打印出來,我可以正確讀取日文字符),但它們可能是實際上編碼在其他字符集,也允許日語字符。我相信有python函數可以告訴你一個字符串的編碼,甚至改變它。 – Cesc