今天寫pytho腳本時遇到幾個基礎問題,在此記錄下
1 中文字符輸出
一個print打印中 含有英文和中文字符,因為中文編碼問題,print報錯 ascii code cant decode byte 0xef in position 0
python字符串分byte str 和unicode str兩種,指定編碼方式為UTF8,則所有中文字符串都認為是byte str 而函數中產生字符串是unicode str 兩者混合輸出時就會導致中文字符問題
有兩個解決方案
1)將字符串轉成byte str
(“你好"+self.request.get(“argu”).encode(“utf-8”))
2)將字符串轉成unicode str
(u“你好"十self.request.get(“argu"))
腳本輸出本地英文字符 十 mysql 獲取中文字符(mysql字符集是utf8) OK
本地中文十mysqL結果 產生報錯
解決方式參照上面2)
自己模仿本地中文十自定義函數返回字符 也沒有編碼問題,難道是接口函數才有這問題?
附錄:
decode encode
str ---------> str(Unicode) ---------> str
u = '中文' # 指定字符串類型對象u
str1 = u.encode('gb2312') # 以gb2312編碼對u進行編碼,獲得bytes類型對象
print(str1)
b'\xd6\xd0\xce\xc4'
str2 = u.encode('gbk') # 以gbk編碼對u進行編碼,獲得bytes類型對象
print(str2)
b'\xd6\xd0\xce\xc4'
str3 = u.encode('utf-8') # 以utf-8編碼對u進行編碼,獲得bytes類型對象
print(str3)
b'\xe4\xb8\xad\xe6\x96\x87'
u1 = str1.decode('gb2312') # 以gb2312編碼對字符串str進行解碼,獲得字符串類型對象
print('u1')
'中文'
u2 = str1.decode('utf-8') # 報錯,因為str1是gb2312編碼的
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 0: invalid continuation byte
2 換行問題
print 后 帶 , 不會自動換行
3 in匹配
opt in ('proxyaa','proxyb') #全字符串匹配
opt in('proxyaa') #子串匹配
if opt == proxy 會匹配到opt in('proxyaa') 子串