泰州網(wǎng)站建設(shè)服務(wù)熱線寧德市委書(shū)記
平時(shí)我們進(jìn)行大小寫轉(zhuǎn)換基本都是使用upper和lower函數(shù),使用方法:
s = 'Hello,Python123'#大寫轉(zhuǎn)小寫
s.lower()
-->'hello,python123'#小寫轉(zhuǎn)大寫
s.upper()
-->'HELLO,PYTHON123'
但是如果想把字符串中的大寫字母轉(zhuǎn)成小寫,小寫字母轉(zhuǎn)成大寫,上面兩個(gè)函數(shù)就不再適用了,如下代碼,函數(shù)ord是用于返回一個(gè)字符的unicode編碼,大寫字母A-Z比小寫字母a-z小32,利用大小寫字母的unicode編碼進(jìn)行轉(zhuǎn)換,chr函數(shù)則是把相應(yīng)的unicode編碼轉(zhuǎn)換為字符。
s = 'Hello,Python123'def lower_upper(x):lst = []for item in x:if 'A'<=item<='Z':lst.append(chr(ord(item)+32))elif 'a'<=item<='z':lst.append(chr(ord(item)-32))else:lst.append(item)return ''.join(lst)lower_upper(s)
-->'hELLO,pYTHON123'