如何修复配置解析器上的 Unicode 问题



我使用 Python 3.7 和配置解析器 3.7.4.

我有一个等级.ini:

[example]
placeholder : U0001F882

我有一个 main.py 文件:

import configparser
config = configparser.ConfigParser()
config.read('ranks.ini')
print('🢂')
test = 'U0001F882'
print(type(test))
print(test)
test2 = config.get('example', 'placeholder')
print(type(test2))
print(test2)

代码的结果是:

🢂
<class 'str'>
🢂
<class 'str'>
U0001F882

为什么var test2不是"🢂"以及我如何修复它。

我花了一段时间才弄清楚这个问题,因为 python3 将所有内容都视为此处解释的 unicode

如果我的理解是正确的,那么原始印刷品就是这样u'U0001F882',所以它会将其转换为字符。

但是,当您使用配置解析器将变量作为字符串传递时,unicode 转义字符基本上会丢失,例如 '\U0001F882' .

如果您打印 test 和 test2 的 repr 可以看到这种差异

print(repr(test))
print(repr(test2))

要获得所需的输出,您必须对字符串值进行 unicode 转义

print(test2.encode('utf8').decode('unicode-escape')  

希望这对你有用。

最新更新