字符串類型判斷與轉換
一、字節字符串和unicode字符串
1、basestring
在python中字符串的相關數據類型為str和unicode,他們都是basestring的子類,可見str和unicode是兩種不同類型的字符串對象。
2、創建字符串
byteString='hello string'
unicodeString=u'hello string'
type()查看變量類型
二、判斷是否是字符串(str和unicode):
1、用isinstance()函數判斷:判斷一個對象的變量類型,如果是返回True,不是返回False
# encoding=utf-8 byteString='hello normal string' unicodeString=u'hello unicode' if isinstance(byteString,basestring): print byteString, u'是字符串' if isinstance(unicodeString,basestring): print unicodeString,u'是字符串' 運行結果: hello string 是字符串 hello unicode 是字符串
2、判斷是否是unicode:
# encoding=utf-8 byteString='hello normal string' unicodeString=u'hello unicode' if isinstance(byteString,unicode): print byteString, u'是unicode' if isinstance(unicodeString,unicode): print unicodeString,u'是unicode'
運行結果: hello unicode 是unicode
3、判斷是否是str:
byteString='hello string' unicodeString=u'hello unicode' if isinstance(byteString,str): print byteString, u'是str' if isinstance(unicodeString,str): print unicodeString,u'是str'
運行結果: hello string 是str
三、不同字符串類型互轉
1、不指定編碼解碼類型進行互轉--使用系統默認編碼:
s='hello string' print type(s) u=s.decode() #str 轉 unicode print type(u) backToStr=u.encode() #unicode 轉 str print type(backToStr)
運行結果: <type 'str'> <type 'unicode'> <type 'str'>
2、指定編碼解碼類型進行轉換:
# encoding=utf-8 s='hello string' print type(s) u=s.decode('utf-8') #str 轉 unicode print type(u) backToStr=u.encode('utf-8') #unicode 轉 str print type(backToStr) 運行結果: <type 'str'> <type 'unicode'> <type 'str'>