轉換大小寫python
和其餘語言同樣,Python爲string對象提供了轉換大小寫的方法:upper() 和 lower()。還不止這些,Python還爲咱們提供了首字母大寫,其他小寫的capitalize()方法,以及全部單詞首字母大寫,其他小寫的title()方法。函數較簡單,看下面的例子:api
s = 'hEllo pYthon'函數
print s.upper()spa
print s.lower()orm
print s.capitalize()對象
print s.title()字符串
輸出結果:string
HELLO PYTHONit
hello pythonimport
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, strset):
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