第一种方式:html
在python脚本开始的地方加入指定编码方式python
# -*- coding : UTF-8 -*-bash
第二种方式:app
有些时候咱们会获得这种格式的字符串:this
"name": "\u6843\u674e\u9999\u677e\u86cb\u7cd5"
编码
可是在python console中若是输入,则会这样:spa
>>>a = "\u6843\u674e\u9999\u677e\u86cb\u7cd5"
>>>a
>>>'桃李香松蛋糕'
>>>type(a)
>>><class 'str'>code
貌似不用转编码就是中文啊,可是为何仍是非中文呢,因此就须要以下的转换:htm
若是type(text) is bytes,那么text.decode('unicode_escape')
utf-8
若是type(text) is str,那么text.encode('latin-1').decode('unicode_escape')
第三种方式:
IDE Encoding
和project Encoding
(推荐都设置成utf-8)第四种方式:
PyCharm creates files using the IDE encoding defined in the File Encodings page of the Settings dialog, which can be either system default, or the one selected from list of available encodings. Output in the consoles is also treated in this encoding.
It is possible that encoding used in the console output is different from the IDE default. To have PyCharm properly parse text in the console, you have to do some additional editing.
Open for editing PYCHARM_HOME/bin/pycharm.exe.vmoptions
orPYCHARM_HOME/bin/pycharm.vmoptions
-Dconsole.encoding=<encoding name>
-Dconsole.encoding=UTF-8
In macOS: Open Info.plist
located in /应用程序/PyCharm/Contents/, locate the tag <key>VMOptions</key>
, and modify it as follows:
<key>VMOptions</key> <string>-Xms16m -Xmx512m -XX:MaxPermSize=120m -Xbootclasspath/p:../lib/boot.jar -ea -Dconsole.encoding=<encoding name> </string>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
处理方式:将对对应的中文进行一次utf-8编码
text = u'你是好样的'text = text.encode('utf-8')