如何修复 configparser 上的 unicode 问题
how to fix the unicode problem on configparser
我使用 Python 3.7 和
配置解析器 3.7.4.
我有一个 rank.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 解释的 here
如果我的理解是正确的,原来的打印是这样的u'\U0001F882'
,所以它把它转换成字符。
但是,当您使用 configparser 将变量作为字符串传递时,unicode 转义字符基本上会丢失,例如 '\U0001F882'
.
如果打印 test 和 test2 的 repr,您可以看到这种差异
print(repr(test))
print(repr(test2))
要获得您想要的输出,您必须对字符串值进行 unicode 转义
print(test2.encode('utf8').decode('unicode-escape')
希望这对你有用。
我使用 Python 3.7 和 配置解析器 3.7.4.
我有一个 rank.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 解释的 here
如果我的理解是正确的,原来的打印是这样的u'\U0001F882'
,所以它把它转换成字符。
但是,当您使用 configparser 将变量作为字符串传递时,unicode 转义字符基本上会丢失,例如 '\U0001F882'
.
如果打印 test 和 test2 的 repr,您可以看到这种差异
print(repr(test))
print(repr(test2))
要获得您想要的输出,您必须对字符串值进行 unicode 转义
print(test2.encode('utf8').decode('unicode-escape')
希望这对你有用。