python - 打印带有 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'\\')
不起作用。
解决方案
使用raw_unicode_escape
:
text = 'Cze\u00c5\u009b\u00c4\u0087'
text_bytes = text.encode('raw_unicode_escape')
print(text_bytes.decode('utf8')) # outputs Cześć
推荐阅读
- spring-boot - 当方法中发生错误时,会一次又一次地调用 JmsListener
- cassandra - 尝试在 Windows 10 上运行 Cassandra 时遇到一些奇怪的问题
- git - 如何从我没有强制推送权限的主分支中删除包含其历史记录的文件(删除历史记录很重要)?
- python - 是否有任何直接的方式/方法来验证推文是否存在?
- python - Discord.py:根据消息得到的反应来编辑机器人发送的消息
- python - Plotly Sankey 图表在存在循环时切断
- c - 没有返回变量的线程池
- python - 在哪里可以找到 googleapiclient 库中所有查询参数的文档?
- azure-devops - 在扩展模板中设置名称在 azure yaml 管道中不起作用
- timer - ATSAML21 硬件定时器