简体   繁体   中英

Unicode characters not printing properly in terminal python

I have a really simple program that I wrote to tell me the unicode values for some characters.

Here is the program:

#!/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")

and it gives this output:

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

I notice that the output is formatted properly when I copy and paste here but on my computer the second line is displayed like this in the terminal

has the unicode value : 1489 ב 

also I tried putting the output into a file and viewing the file with vim and it also looks like this, with the character that should be printed first being printed last. This leads me to think that it is printing properly but not displaying properly. What could cause this to happen?

The right-justified behaviour of Hebrew characters can be overridden using the Unicode LEFT-RIGHT OVERRIDE (LRO) character 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")

Gives (on OS X Terminal):

‭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

Thanks to @guribe94 in identifying the issue.

You might find string formatting a little easier to read:

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

只需将第一行替换为:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM