我的 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 字符串,是时候进行转换了。
我是一名优秀的程序员,十分优秀!