標籤:預設 apc 系統預設 python ase src color encoding 小練習
一:學習內容
二:字串類型
1. basestring
在python中和字串相關的資料類型為:str和unicode,他們都是basestring的子類,可見str和unicode是兩種不同類型的字串對象
2. 位元組字串類型
byteString=‘hello world!‘
可以看到這個byteString的類型為str
3. unicode字串類型(在一般字元串前面加個u)
unicodeString=u‘hello Unicode world!‘
可以看到這個unicodeString的類型為unicode
三:字串類型判斷
1. 判斷是否是字串(包括str和unicode)
#encoding=utf-8
s = "hello normal string"
u = u‘hello unicode‘
if isinstance(s,basestring):
print u‘是字串‘
if isinstance(u,basestring):
print u‘是字串‘
運行結果為:無論是str字串還是unicode字串都屬於basestring類中子類
2. 判斷是否是unicode
#encoding=utf-8
s = "hello normal string"
u = u‘hello unicode‘
if isinstance(s,unicode):
print s,u‘是unicode‘
if isinstance(u,unicode):
print u,u‘是unicode‘
運行結果為:
3. 判斷是否是str
#encoding=utf-8
s = "hello normal string"
u = u‘hello unicode‘
if isinstance(s,str):
print s,u‘是str‘
if isinstance(u,str):
print u,u‘是str‘
運行結果為:
四:字串類型互轉
1. 不指定編碼解碼類型進行互轉-使用系統預設編碼
#encoding=utf-8
s="byte string"
print type(s)
#str 轉 unicode
u = s.decode()
print type(u)
#uncode 轉 str
backToBytes = u.encode()
print type(backToBytes)
可以看到上面的unicode和decode都沒有指定編碼解碼的名稱,此時會用系統預設的編碼。
2. 指定編碼解碼類型進行互轉
#encoding=utf-8
s = "hello normal string"
print u"位元組字串",type(s)
#str 轉 unicode
u = s.decode("UTF-8" )
print u"Unicode字串",type(u)
#uncode 轉 str
backToBytes = u.encode( "UTF-8" )
print u"位元組字串",type(backToBytes)
運行結果為:
五:字串小練習
1. 小練習一:輸出字元串中奇數座標的字串
a = ‘gloryroad‘
‘‘.join([a[x] for x in xrange(len(a)) if x%2==1])
2. 小練習二:將字串大寫變小寫,小寫變大寫輸出
s=‘adbABC‘
s.swapcase()
3. 小練習三:將字串abcdefgccc順序第一個c變成f然後輸出整個字串
s1=‘abcdefgccc‘
s2=‘‘
flag=True
for i in s1:
if i==‘c‘ and flag:
s2+=‘f‘
flag=False
else:
s2+=i
print s2
運行結果為:
4. 小練習四:輸出1000以內包含3的數如:34,153等
print [x for x in range(1001) if ‘3‘ in str(x)]
上面的練習也許各位初學者不能全部都看懂,別急,後續的python學習筆記中我們會就每一個細節進行一一學習。
筆記五:python字串