gpt4 book ai didi

python - 如何在 unicode 中读取 oslo 配置值

转载 作者:太空宇宙 更新时间:2023-11-04 06:02:57 25 4
gpt4 key购买 nike

我的 nova.conf 文件中有一些日文字符。

kura

从配置文件中读取后,我必须将其解码为 utf-8

my_data = CONF.test.test
my_data = my_data.decode('utf-8')

当我在没有解码的情况下使用变量时,它给出 UnicodeDecodeError

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128)

有什么方法可以直接从配置中读取解码后的数据吗?

最佳答案

Is there any way to read data from config directly in decoded form?

不在 python 2.7 中。因为在 python 3 之前的 python 中,字符串默认为 ASCII 字符串,而在 python 3 中,字符串默认为 unicode 字符串。所以基本上:

>>> mydata = "クラ"
>>> print mydata.decode('utf-8')
クラ
>>> print mydata
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128)

而在 python 3 中:

>>> mydata = "クラ"
>>> print(mydata)
クラ

因此,如果您想轻松处理 unicode 字符串,是时候进行转换了。

关于python - 如何在 unicode 中读取 oslo 配置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23777665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com