首页 > 解决方案 > 打印带有 UTF-8 编码字符的字符串,例如:“\u00c5\u009b\”

问题描述

我想打印这样编码的字符串:"Cze\u00c5\u009b\u00c4\u0087"但我不知道如何。示例字符串应打印为:“Cześć”。

我尝试过的是:

str = "Cze\u00c5\u009b\u00c4\u0087"
print(str) 
#gives: CzeÅÄ

str_bytes = str.encode("unicode_escape")
print(str_bytes) 
#gives: b'Cze\\xc5\\x9b\\xc4\\x87'

str = str_bytes.decode("utf8")
print(str) 
#gives: Cze\xc5\x9b\xc4\x87

在哪里

print(b"Cze\xc5\x9b\xc4\x87".decode("utf8"))

给出“Cześć”,但我不知道如何将"Cze\xc5\x9b\xc4\x87"字符串转换为b"Cze\xc5\x9b\xc4\x87"字节。

我也知道问题是在使用"unicode_escape"参数编码基本字符串后字节表示中的额外反斜杠,但我不知道如何摆脱它们 -str_bytes.replace(b'\\\\', b'\\')不起作用。

标签: pythonpython-3.xpython-unicode

解决方案


使用raw_unicode_escape

text = 'Cze\u00c5\u009b\u00c4\u0087'
text_bytes = text.encode('raw_unicode_escape')
print(text_bytes.decode('utf8')) # outputs Cześć

推荐阅读