python - 字符'ñ'的Python Unicode转换
问题描述
我必须打印 char 'ñ' 的 Unicode 例如输入 - 'Piñeiro' 输出 - 'Pi\xf1eiro'(使用的编解码器 - raw_unicode_escape) 预期 - 'Pi\u00f1eiro'
我尝试了来自https://docs.python.org/3/library/codecs.html#text-encodings的其他标准编码和文本编码编解码器, 但似乎表中没有一个是产生所需的输出
关于需要哪个编码模块来获得所需输出的任何建议?
解决方案
如果你试图打印出Pi\u00f1eiro
——一个长度为 11 的字符串——而不是Piñeiro
——一个长度为 7 的字符串,你可以这样做
In [93]: mytext = "Pi\u00f1eiro"
In [94]: print(mytext)
Piñeiro
In [95]: new_text = "".join(["\\u{:04x}".format(ord(c)) if ord(c) > 0x7f else c for c in mytext])
In [96]: print(new_text)
Pi\u00f1eiro
In [97]: new_text
Out[97]: 'Pi\\u00f1eiro'
如何确定要显示的字符取决于您。我有点随意选择了任何unicode 代码单元大于007F的字符。
推荐阅读
- powerbi - Power BI - 如何限制使用日期导入的数据
- python - 如何在 pandas 中读取 AM/PM 时间?
- swift - 如何在 VStack 中为子视图排列底部文本
- vector - 在 Rust 中,当向量 v 的大小为 1 时,为什么 &v[1..] 不恐慌?
- javascript - API Fetch 问题:未处理的承诺拒绝:SyntaxError:JSON 解析错误:意外的标识符“服务器”
- azure - 使用 REST API 在 Go 中对 Azure 进行身份验证
- google-bigquery - 无论存储引擎类型如何,它们是否支持单个 DDL 和 DML SQL 语句的事务?
- visual-studio-code - 在当前 VSCode 目录中打开 WSL 终端而不使用 VSCode 服务器
- android - 为什么firebase身份验证返回null?
- python - 使用 Spacy nlp 合并两个 CSV 文件