Python 字串 isupper() 方法



Python 字串 isupper() 方法用於確定給定字串中所有基於大小寫的字元或字母是否都為大寫。大小寫字元是指其通用類別屬性為“Ll”(字母,小寫),“Lu”(字母,大寫)或“Lt”(字母,標題大小寫)的字元。

大寫定義為以其大寫形式書寫或列印的字母,也稱為大寫字母。

例如,如果給定單詞“ProGRaMmINg”中的大寫字母為 P、G、R M、I 和 N。

注意:不會檢查給定字串中的數字、符號和空格,僅考慮字母字元。

語法

以下是 Python 字串 isupper() 方法的語法

str.isupper()

引數

此方法不接受任何引數。

返回值

如果字串中所有大小寫字元都為大寫,並且至少存在一個大小寫字元,則此方法返回 True,否則返回 False。

示例

當我們傳遞字串中所有字母都為大寫時,它返回 True。

在以下示例中,建立了一個字串“PYTHON”,所有字母都為大寫。然後使用 Python 字串 isupper() 方法檢查給定字串是否為大寫。然後檢索結果。

# initializing the string
Given_string = "PYTHON"
# Checking whether the string is in uppercase
res = Given_string.isupper()
# Printing the result
print ("Is the given string in uppercase?: ", res)

以上程式碼的輸出如下

Is the given string in uppercase?:  True

示例

如果字串中所有字母都為小寫,則返回 False。

以下是一個示例,其中建立了一個字串“this is string example....wow!!!”。然後使用 isupper() 方法檢索結果,說明給定字串是否為大寫。

# initialize the string
str = "this is string example....wow!!!";
print (str.isupper())

以下以上程式碼的輸出

False

示例

在下面給出的示例中,使用 for 迴圈計算給定句子中所有大寫單詞的計數。首先,建立一個字串。然後將字串分割並透過計數大寫單詞來檢索結果

# initializing the string
Given_string = "python IS a PROGRAMMING language"
res = Given_string.split()
count = 0
# Counting the number of uppercase
for i in res:
   if (i.isupper()):
      count = count + 1
# Printing the result
print ("The number of uppercase words in the sentence is: ", str(count))

執行以上程式碼時,我們將獲得以下輸出

The number of uppercase words in the sentence is:  2

示例

在以下示例中,建立了一個包含數字、符號和字母的字串,以檢查它是否為大寫

# initializing the string
Given_string = "Cod3iN#g"
# Checking whether the string is in uppercase
res = Given_string.isupper()
# Printing the result
print ("Is the given string in uppercase?: ", res)

當我們執行以上程式時,它會產生以下結果

Is the given string in uppercase?:  False
python_strings.htm
廣告