如何在Python中檢查字串是否只包含大寫字母?


字串是字元的集合,可以表示單個單詞或整個語句。字串在Python中易於使用,因為它們不需要顯式宣告,並且可以用或不用說明符定義。Python具有各種內建函式和方法來操作和訪問字串。因為Python中的所有內容都是物件,所以字串是String類的物件,具有多種方法。

在本文中,我們將瞭解如何在Python中檢查字串是否只包含大寫字母。

使用isupper()函式

驗證大寫字母的一種方法是使用字串庫的isupper()函式。如果當前字串中的每個字元都是大寫字母,則此函式返回True;否則,返回False

示例1

在下面給出的示例中,我們取兩個字串str1和str2,並檢查它們是否包含除小寫字母以外的任何字元。我們藉助isupper()函式進行檢查。

str1 = 'ABCDEF' str2 = 'Abcdef' print("Checking whether",str1,"is upper case") print(str1.isupper()) print("Checking whether",str2,"is upper case") print(str2.isupper())

輸出

上述程式的輸出為:

('Checking whether', 'ABCDEF', 'is upper case')
True
('Checking whether', 'Abcdef', 'is upper case')
False

示例2

以下是使用isupper()函式的另一個示例。在下面給出的程式中,我們檢查如果大寫單詞之間有空格會發生什麼。

str1 = 'WELCOME TO TUTORIALSPOINT' print("Checking whether",str1,"is upper case") print(str1.isupper())

輸出

上述程式的輸出為:

('Checking whether', 'WELCOME TO TUTORIALSPOINT', 'is upper case')
True

使用正則表示式

我們還可以使用正則表示式來確定給定字串是否包含小寫字母。

為此,匯入re庫,如果尚未安裝,則安裝它。匯入re庫後,我們將使用正則表示式“[A-Z]+$”。如果字串包含任何非大寫字元,則返回False;否則,返回True

示例

在下面給出的程式中,我們使用正則表示式“[A-Z]+$”來檢查給定的字串是否為大寫。

import re str1 = 'ABCDEF' str2 = 'Abcdef' print("Checking whether",str1,"is upper case") print(bool(re.match('[A Z]+$', str1))) print("Checking whether",str2,"is uppercase") print(bool(re.match('[A Z]+$', str2)))

輸出

上述程式的輸出為:

('Checking whether', 'ABCDEF', 'is upper case')
False
('Checking whether', 'Abcdef', 'is uppercase')
False

使用ASCII值

我們可以遍歷字串的每個字元,並根據ASCII值進行驗證。我們知道大寫字元的ASCII值介於65和90之間。如果每個ASCII值都大於64且小於91,則返回True;否則,返回false。

示例

在下面給出的示例中,我們編寫了一個函式checkupper()並比較該字串中每個字元的ASCII值。

def checkupper(str1): n = len(str1) count = 0 for i in str1: if(64<ord(i) <91): count += 1 if count == n: return True return False str1 = 'ABCDEF' str2 = 'Abcdef' print("Checking whether",str1,"is upper case") print(checkupper(str1)) print("Checking whether",str2,"is upper case") print(checkupper(str2))

輸出

上述程式的輸出為:

('Checking whether', 'ABCDEF', 'is upper case')
True
('Checking whether', 'Abcdef', 'is upper case')
None

更新於:2022年10月19日

8K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告