首頁  >  文章  >  後端開發  >  python中轉換大小寫的方法

python中轉換大小寫的方法

Y2J
Y2J原創
2017-05-18 14:54:127129瀏覽

和其他語言一樣,Python為string物件提供了轉換大小寫的方法:upper() 和 lower()。不只這些,Python也為我們提供了首字母大寫,其餘小寫的capitalize()方法,以及所有單字首字母大寫,其餘小寫的title()方法。

函數較簡單,看下面的範例:

 程式碼如下:

s = 'hEllo pYthon' 
print
 s.upper() 
print s.lower() 
print s.capitalize() 
print s.title()

輸出結果:

HELLO PYTHON 
hello python 
Hello python 
Hello Python

判斷大小寫
Python提供了isupper(),islower(),istitle()方法用來判斷字串的大小寫。注意的是:
1. 沒有提供 iscapitalize()方法,下面我們會自己實現,至於為什麼Python沒有為我們實現,就不得而知了。
2. 如果對空字串使用isupper(),islower(),istitle(),傳回的結果都為False。

程式碼如下:

print 'A'.isupper() #True 
print 'A'.islower() #False 
print 'Python Is So Good'.istitle() #True 
#print 'Dont do that!'.iscapitalize() #错误,不存在iscapitalize()方法

實作iscapitalize
1. 如果我們只是簡單比較原字串與進行了capitallize()轉換的字串的話,如果我們傳入的原字串為空字串的話,回傳結果會為True,這不符合我們上面提到的第2點。
def iscapitalized(s):
return s == s.capitalize( )有人想到返回時加入條件,判斷len(s)>0,其實這樣是有問題的,因為當我們呼叫iscapitalize( '123')時,回傳的是True,不是我們預期的結果。
2. 因此,我們回想起了先前的translate方法,去判斷字串是否包含任何英文字母。實作如下:

 程式碼如下:

import string 
notrans = string.maketrans('', '') 
def containsAny(str, str
set
): 
return len(strset) != len(strset.translate(notrans, str)) 
def iscapitalized(s): 
return s == s.capitalize( ) and containsAny(s, string.letters) 
#return s == s.capitalize( ) and len(s) > 0 #如果s为数字组成的字符串,这个方法将行不通调用一下试试: 
print iscapitalized('123') 
print iscapitalized('') 
print iscapitalized('Evergreen is zcr1985')

輸出結果:

False 
False 
True

【相關建議】

##1. 

# Python免費視訊教學

2. 

詳解python中lower與upper函數的使用

3. 

python基礎入門之upper簡介

以上是python中轉換大小寫的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn