python 字符串 大小寫轉換 以及一系列字符串操作技巧


 

總結

capitalize() 首字母大寫,其余全部小寫
  upper() 全轉換成大寫
  lower() 全轉換成小寫
  title() 標題首字大寫,如"i love python".title() "I Love Python"

 

轉換大小寫

和其他語言一樣,Python為string對象提供了轉換大小寫的方法:upper() 和 lower()。還不止這些,Python還為我們提供了首字母大寫,其余小寫的capitalize()方法,以及所有單詞首字母大寫,其余小寫的title()方法。函數較簡單,看下面的例子:

python 字符串 大小寫轉換 - 波博 - A Pebble Caves = 'hEllo pYthon'

python 字符串 大小寫轉換 - 波博 - A Pebble Caveprint s.upper()

python 字符串 大小寫轉換 - 波博 - A Pebble Caveprint s.lower()

python 字符串 大小寫轉換 - 波博 - A Pebble Caveprint s.capitalize()

python 字符串 大小寫轉換 - 波博 - A Pebble Caveprint s.title()

輸出結果:

HELLO PYTHON

hello python

Hello python

Hello Python

判斷大小寫

Python提供了isupper(),islower(),istitle()方法用來判斷字符串的大小寫。注意的是:

1. 沒有提供 iscapitalize()方法,下面我們會自己實現,至於為什么Python沒有為我們實現,就不得而知了。

2. 如果對空字符串使用isupper(),islower(),istitle(),返回的結果都為False。

python 字符串 大小寫轉換 - 波博 - A Pebble Caveprint 'A'.isupper() #True

python 字符串 大小寫轉換 - 波博 - A Pebble Caveprint 'A'.islower() #False

python 字符串 大小寫轉換 - 波博 - A Pebble Caveprint 'Python Is So Good'.istitle() #True

python 字符串 大小寫轉換 - 波博 - A Pebble Cave#print 'Dont do that!'.iscapitalize() #錯誤,不存在iscapitalize()方法

實現iscapitalize

1. 如果我們只是簡單比較原字符串與進行了capitallize()轉換的字符串的話,如果我們傳入的原字符串為空字符串的話,返回結果會為True,這不符合我們上面提到的第2點。

python 字符串 大小寫轉換 - 波博 - A Pebble Cavedef iscapitalized(s):

python 字符串 大小寫轉換 - 波博 - A Pebble Cave    return s == s.capitalize( )

有人想到返回時加入條件,判斷len(s)>0,其實這樣是有問題的,因為當我們調用iscapitalize('123')時,返回的是True,不是我們預期的結果。

2. 因此,我們回憶起了之前的translate方法,去判斷字符串是否包含任何英文字母。實現如下:

python 字符串 大小寫轉換 - 波博 - A Pebble Caveimport string

python 字符串 大小寫轉換 - 波博 - A Pebble Cavenotrans = string.maketrans('', '')

python 字符串 大小寫轉換 - 波博 - A Pebble Cavedef containsAny(str, strset):

python 字符串 大小寫轉換 - 波博 - A Pebble Cave    return len(strset) != len(strset.translate(notrans, str))

python 字符串 大小寫轉換 - 波博 - A Pebble Cavedef iscapitalized(s):

python 字符串 大小寫轉換 - 波博 - A Pebble Cave    return s == s.capitalize( ) and containsAny(s, string.letters)

python 字符串 大小寫轉換 - 波博 - A Pebble Cave    #return s == s.capitalize( ) and len(s) > 0 #如果s為數字組成的字符串,這個方法將行不通

調用一下試試:

python 字符串 大小寫轉換 - 波博 - A Pebble Caveprint iscapitalized('123')

python 字符串 大小寫轉換 - 波博 - A Pebble Caveprint iscapitalized('')

python 字符串 大小寫轉換 - 波博 - A Pebble Caveprint iscapitalized('Evergreen is zcr1985')

輸出結果:

False

False

True

 

取出字符串中包含的數字

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM