如何在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+ 次檢視

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告