2017-05-22 55 views
0

我正在閱讀與python 3.5 json文件。在這個文件中它有像「í」的字符。我想以這種格式打印它。如何讓下面的代碼正確地打印字符?Python閱讀字符串'í'並打印它

t = 'í' 
print(t) 

Traceback (most recent call last): 
    File "test.py", line 15, in <module> 
    print(t) 
UnicodeEncodeError: 'ascii' codec can't encode character '\xed' in position 0: ordinal not in range(128) 
+0

[UnicodeEncodeError的可能重複: 'ASCII' 編解碼器不能編碼字符U位置20 '\ XA0':主要是有序不範圍(128)](http://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20) –

+1

我不能再現這 - 它打印對於我來說足夠了。你確定你在使用Python 3嗎?在這種情況下,只有Python 2應該有這個錯誤。 –

+1

這就是你使用Python 2運行時得到的錯誤 – abccd

回答

0

使用unicode格式。

t = u'i' 
print(t) 

你有字符「我」這樣Python理解它爲Unicode之前添加u

+0

在你輸入文字的情況下,這是真的。 OP的用例是從文件中讀取字符串的呢? –

+0

OP想'í'不'我',它不會工作 – abccd

+0

我們可以在導入json文件時指定編碼 – bigbounty

1

嘗試添加# -*- coding: iso-8859-15 -*-作爲源文件的第一行或第二行。

0

試試這個:

print(t.decode("utf-8")) 
0

試試這個 -

# -*- coding: utf-8 -*- 
from __future__ import unicode_literals 
t = 'í' 
print(t.encode("ascii" , "ignore"))