2017-06-02 70 views
0

我將數據打印到標準輸出存在問題。我理解Unicode和Ascii的概念,但我不明白爲什麼打印指令不起作用。Unicode,打印到標準輸出,發生了什麼?

我在玩電腦遊戲的JSON文件中的數據,Fallout Shelter。

當我試圖與打印數據:

for i in jsondata["dwellers"]["dwellers"]: 
     print "{},{} {},{}".format(f,i["name"],i["lastName"],i["relations"]) 

我得到一個錯誤:

Traceback (most recent call last): 
    File "f:\FOSScript\Tree.py", line 81, in <module> 
    tree() 
    File "f:\FOSScript\Tree.py", line 76, in tree 
    graphing(jsondata) 
    File "f:\FOSScript\Tree.py", line 35, in graphing 
    print "{} {}".format(i["name"],i["lastName"]) 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128) 

的U '\ xe9' 是一個法國口音。

但在代碼中,當我這樣做:

prenom = u'Val\xe9rie' 
print prenom 

名稱正確打印。

以下說明:

print locale.getpreferredencoding() 
print sys.stdout.encoding 

打印如下:

cp1252 
cp850 

兩個代碼頁(如查了維基百科)包含重音字符。

我在Windows 10上,一個法國加拿大版本。 Python 2.7.13。

==========================

  • 爲什麼從表打印不工作,但印刷變量有效嗎?

  • this頁,有評論說

的Python中唯一支持的默認編碼是:

的Python 2.x的:ASCII
的Python 3.X:UTF -8

當他們說ASCII時,他們的意思是帶有重音的擴展ASCII,因爲JSON數據包含重音符,python只是「無法」打印它?

謝謝!

回答

1

問題是您試圖在unicode字符的非unicode字符串上使用字符串格式。相反,你想要:

for i in jsondata["dwellers"]["dwellers"]: 
     print u"{},{} {},{}".format(f,i["name"],i["lastName"],i["relations"]) 

注意在第二行報價之前的額外u。

測試這對蟒蛇2.7

print u"{}".format(u'\xe9') 

工作正常。

相關問題