首页 > 解决方案 > 字符'ñ'的Python Unicode转换

问题描述

我必须打印 char 'ñ' 的 Unicode 例如输入 - 'Piñeiro' 输出 - 'Pi\xf1eiro'(使用的编解码器 - raw_unicode_escape) 预期 - 'Pi\u00f1eiro'

我尝试了来自https://docs.python.org/3/library/codecs.html#text-encodings的其他标准编码和文本编码编解码器, 但似乎表中没有一个是产生所需的输出

关于需要哪个编码模块来获得所需输出的任何建议?

标签: python

解决方案


如果你试图打印出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的字符。


推荐阅读