2016-03-01 44 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''。 –