如何在Python 2.7中打印像“u {variable}”这样的Unicode?

时间:2018-04-21 16:50:58

标签: python unicode python-unicode

例如,我可以打印Unicode符号,如:

print u'\u00E0'

或者

a = u'\u00E0'
print a

但看起来我不能做这样的事情:

a = '\u00E0'
print someFunctionToDisplayTheCharacterRepresentedByThisCodePoint(a)

主要用例将在循环中。我有一个unicode代码点列表,我希望在控制台上显示它们。类似的东西:

with open("someFileWithAListOfUnicodeCodePoints") as uniCodeFile:
    for codePoint in uniCodeFile:
        print codePoint #I want the console to display the unicode character here

该文件包含一个unicode代码点列表。例如:

2109
OOBO
00E4
1F1E6

循环应输出:

℉
°
ä
  

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:4)

这可能不是一个好方法,但它是一个开始:

>>> x = '00e4'
>>> print unicode(struct.pack("!I", int(x, 16)), 'utf_32_be')
ä

首先,我们得到十六进制字符串x表示的整数。我们将其打包成一个字节字符串,然后我们可以使用utf_32_be编码进行解码。

由于您正在执行此操作,因此可以预编译结构:

int2bytes = struct.Struct("!I").pack
with open("someFileWithAListOfUnicodeCodePoints") as fh:
    for code_point in fh:
        print unicode(int2bytes(int(code_point, 16)), 'utf_32_be')

如果您认为它更清楚,您也可以直接使用decode方法而不是unicode类型:

>>> print int2bytes(int('00e4', 16)).decode('utf_32_be')
ä

Python 3为to_bytes类添加了int方法,允许您绕过struct模块:

>>> str(int('00e4', 16).to_bytes(4, 'big'), 'utf_32_be')
"ä"

答案 1 :(得分:1)

你想要print unichr(int('00E0',16))。将十六进制字符串转换为整数并打印其Unicode代码点。

警告:在Windows代码点> U + FFFF不起作用。

解决方案:使用Python 3.3+ print(chr(int(line,16)))

在所有情况下,您仍然需要使用支持代码点字形的字体。

答案 2 :(得分:0)

这些是unicode代码点但缺少\u python unicode-escape。所以,只需将其放入:

with open("someFileWithAListOfUnicodeCodePoints", "rb") as uniCodeFile:
    for codePoint in uniCodeFile:
        print "\\u" + codePoint.strip()).decode("unicode-escape")

这是否适用于给定系统取决于控制台的编码。如果它是一个Windows代码页并且字符不在其范围内,那么您仍然会遇到时髦的错误。

在python 3中b"\\u"

相关问题