AP2*_*257 5 python character-encoding
我正在使用Python处理UTF-8文件,并使用simplejson将其加载到字典中.但是,当我尝试将其中一个字典值转换为字符串时,我收到了UnicodeDecodeError:
f = open('my_json.json', 'r')
master_dictionary = json.load(f)
#some json wrangling, then it fails on this line...
mysql_string += " ('" + str(v_dict['code'])
Traceback (most recent call last):
File "my_file.py", line 25, in <module>
str(v_dict['code']) + "'), "
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf4' in position 35: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
为什么Python甚至使用ASCII?我认为它默认使用UTF-8,输入来自UTF-8文件.
$ file my_json.json
my_json.json: UTF-8 Unicode English text
Run Code Online (Sandbox Code Playgroud)
问题是什么?
Python 2.x默认使用ASCII.使用unicode.encode(),如果你想打开一个unicode到str:
v_dict['code'].encode('utf-8')
Run Code Online (Sandbox Code Playgroud)