如何在 Python 中檢查字元是否為大寫?


在本文中,我們將瞭解如何在 Python 中檢查字元是否為大寫。

第一種方法是使用 isupper() 方法。Python 標準庫有一個內建方法叫做 isupper()。它支援使用字串和其他型別的資料。它顯示一個字元字串是否只包含大寫字母。

如果至少有一個字元是小寫,則返回 FALSE。否則,如果字串中的每個字母都是大寫的,則返回 TRUE。它不需要任何引數。

示例

在下面給出的示例中,我們取 2 個字串作為輸入,並使用 isupper() 方法檢查它們是否為大寫 

str1 = "A"
str2 = "b"

print("Checking if the string '",str1,"' is uppercased or not")
print(str1.isupper())

print("Checking if the string '",str2,"' is uppercased or not")
print(str2.isupper())

輸出

上面示例的輸出如下所示 −

Checking if the string ' A ' is uppercased or not
True
Checking if the string ' b ' is uppercased or not
False

使用正則表示式

正則表示式 用於第二種方法。匯入 re 庫,如果它尚未安裝,則安裝它以使用它。匯入 re 庫後,我們將使用正則表示式 ‘[A-Z]’。如果字元是小寫,則返回 False,否則返回 True。

示例

在下面給出的示例中,我們取 2 個字元作為輸入,並使用正則表示式匹配方法檢查它們是否為大寫 

import re
str1 = "A"
str2 = "b"

print("Checking if the string '",str1,"' is uppercased or not")
print(bool(re.match('[A-Z]', str1)))

print("Checking if the string '",str2,"' is uppercased or not")
print(bool(re.match('[A-Z]', str2)))

輸出

上面示例的輸出如下所示 −

Checking if the string ' A ' is uppercased or not
True
Checking if the string ' b ' is uppercased or not
False

使用 ASCII 值

第三種方法涉及使用 ASCII 值。我們知道小寫字元的 ASCII 值從 97 開始,因此我們需要檢查字元的 ASCII 值是否小於 97。如果 ASCII 值小於 97,則返回 true;否則,返回 false。

示例

在下面給出的示例中,我們取 2 個字元作為輸入,並使用 ord() 方法透過比較 ASCII 值來檢查它們是否為大寫 

def checkupper(str):
   if ord(str) < 96 :
      return True
   return False 
str1 = 'A'
str2 = 'b'

print("Checking whether",str1,"is upper case")
print(checkupper(str1))

print("Checking whether",str2,"is upper case")
print(checkupper(str2))

輸出

上面示例的輸出如下所示 −

Checking whether A is upper case
True
Checking whether b is upper case
False

使用比較

第四種方法是直接比較給定的字元。我們將檢查字元是否大於等於 "A" 或小於等於 "Z"。如果字元在此範圍內,則返回 True,否則返回 False。

示例

在下面給出的示例中,我們取 2 個字元作為輸入,並透過將它們與 "A" 和 "Z" 比較來檢查它們是否為大寫 

def checkupper(str):
   if str >= 'A' and str <= 'Z':
      return True
   else:
      return False
      
str1 = 'A'
str2 = 'b'

print("Checking whether",str1,"is upper case")
print(checkupper(str1))

print("Checking whether",str2,"is upper case")
print(checkupper(str2))

輸出

上面示例的輸出為 −

Checking whether A is upper case
True
Checking whether b is upper case
False

更新於: 2023年8月26日

40K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.