第一種方式: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')