gpt4 book ai didi

python - 打印带有 UTF-8 编码字符的字符串,例如: "\u00c5\u009b\"

转载 作者:行者123 更新时间:2023-11-28 21:36:16 26 4
gpt4 key购买 nike

我想打印这样编码的字符串:"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'\\') 不起作用。

最佳答案

使用raw_unicode_escape:

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

关于python - 打印带有 UTF-8 编码字符的字符串,例如: "\u00c5\u009b\",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51293444/

26 4 0