如何“打印UTF8字符串”

时间:2020-10-12 11:38:02

标签: python unicode

我有一个字符串:

"123456789012"

是否可以像这样打印?

print("\u1234\u5678\u9012")

使用功能?例如print_utf8(string)

1 个答案:

答案 0 :(得分:0)

# Split the string into chunks of length 4
In [1]: codepoints = ["1234", "5678", "9012"]

# Convert them into the `\u` format
In [2]: r'\u' + r'\u'.join(codepoints)                                          
Out[2]: '\\u1234\\u5678\\u9012'

# Decode
In [3]: _.encode().decode('unicode-escape')                                     
Out[3]: 'ሴ噸递'

请注意,在Python 3中,字符串已经使用Unicode。这就是为什么您需要.encode()带有Unicode转义的字符串,然后.decode()。参见decode(unicode_escape) in python 3 a string