2016-03-01 43 views
4

我寫了一個非常簡單的程序,告訴我某些字符的unicode值。Unicode字符在終端python中沒有正確打印

下面是程序:

#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 

characters = [u'T', u'ב', u'€', u'木', u'♥'] 

for character in characters: 

    print(character + " has the unicode value :\t"+str(hex(ord(character))) + "\n") 

,並讓這樣的輸出:

T has the unicode value : 84 

ב has the unicode value : 1489 

€ has the unicode value : 8364 

木 has the unicode value : 26408 

♥ has the unicode value : 9829 

我注意到,當我複製輸出格式正確粘貼在這裏,但我的電腦第二行在終端顯示如下

has the unicode value : 1489 ב 

我也試着把輸出一個文件並用vim查看文件,它看起來像這樣,應該首先打印的字符最後打印。這導致我認爲它正在正確打印,但不能正確顯示。什麼可能導致這種情況發生?

+0

您正在使用什麼版本的Python?如果你正在使用python2,你的代碼應該錯誤 –

+0

@PadraicCunningham,因爲在明顯的Unicode前沒有'u',但它仍然從'ord'給出正確的結果,我會說它是Python 3.哪個子版本我不知道。 –

+0

@MarkRansom,我想雙倍肯定,如果輸出不匹配,它是python3,那麼編碼很可能是問題 –

回答

0

只需更換第一行是:

characters = [u'T', u'ב', u'€', u'木', u'♥'] 
+1

在Python 3中這不是必要的,事實上在早期版本中失敗。 –

+0

它在2.7中對我很好,如果它是unicode字符串,爲什麼它會失敗?事實上,如果它不是unicode字符串,它會崩潰。 – olofom

+0

這沒有什麼區別,就像@MarkRansom所說的,在python 3中這不應該是必要的,因爲Python 3默認將字符串視爲unicode – guribe94

3

的希伯來語字符的右對齊行爲可以使用Unicode左右倍率(LRO)字符0x202D覆蓋。

characters = [u'T', u'ב', u'€', u'木', u'♥'] 

for character in characters: 

    print(chr(0x202D) + character + " has the unicode value :\t"+str(hex(ord(character))) + "\n") 

給出(在OS X終端):

‭T has the unicode value : 0x54 

‭ב has the unicode value : 0x5d1 

‭€ has the unicode value : 0x20ac 

‭木 has the unicode value : 0x6728 

♥ has the unicode value : 0x2665 

感謝@ guribe94識別的問題。

您可能會發現字符串格式化輕鬆一點閱讀:

print("%s%s has the unicode value :\t 0x%04x\n" % 
     (chr(0x202D), character, ord(character))) 
+0

而不是'chr(0x202D)'你可以使用''\ u202d''。 –