第一种方式:
在python脚本开始的地方加入指定编码方式
# -*- coding : UTF-8 -*-
第二种方式:
有些时候我们会得到这种格式的字符串:
"name": "\u6843\u674e\u9999\u677e\u86cb\u7cd5"
但是在python console中如果输入,则会这样:
>>>a = "\u6843\u674e\u9999\u677e\u86cb\u7cd5"
>>>a
>>>'桃李香松蛋糕'
>>>type(a)
>>><class 'str'>
貌似不用转编码就是中文啊,但是为什么还是非中文呢,所以就需要如下的转换:
如果type(text) is bytes,那么text.decode('unicode_escape')
如果type(text) is str,那么text.encode('latin-1').decode('unicode_escape')
第三种方式:
console中文显示乱码问题:
在settings->File encoding界面选择
IDE Encoding
和project Encoding
(推荐都设置成utf-8)
不过这个设置貌似和程序的编码有关,鉴于一般都是万国码。所以还是这样方便点。
第四种方式:
console中显示unicode编码,设置成显示成中文:
Configuring Output Encoding
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.
To set up encoding for the console output, depending on your operating system:
- In Windows and Linux:
Open for editing
PYCHARM_HOME/bin/pycharm.exe.vmoptions
orPYCHARM_HOME/bin/pycharm.vmoptions
respectively, and add the following line at the bottom:
-Dconsole.encoding=<encoding name>For example:
-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')