【问题标题】:how to fix the unicode problem on configparser如何解决 configparser 上的 unicode 问题
【发布时间】:2019-04-01 18:43:12
【问题描述】:

我使用 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 不是 "????"以及我该如何解决它。

【问题讨论】:

    标签: python-3.x configparser


    【解决方案1】:

    我花了一段时间才弄清楚这一点,因为 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')  
    

    希望这对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      • 2012-05-26
      • 2017-08-06
      • 2019-07-11
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多