如何使用 Python 檢查字串是否以大寫字母開頭?


字串是字元的集合,可以表示單個單詞或整個句子。與 Java 不同,無需顯式宣告 Python 字串,我們可以直接將字串值賦給字面量。

Python 中的字串由字串類表示,該類提供多個函式和方法,您可以使用這些函式和方法對字串執行各種操作。

在本文中,我們將瞭解如何使用 Python 檢查字串是否以大寫字母開頭。

使用 isupper() 方法

實現此目的的一種方法是使用內建字串方法isupper()。我們應該使用索引訪問字串的第一個字母,然後將字元傳送到isupper()方法,如果給定字元是大寫,則此方法返回 True,否則返回 False。

示例 1

在下面給出的示例中,我們以字串作為輸入,並使用isupper()方法檢查第一個字母是大寫還是小寫。

str1 = "Welcome to Tutorialspoint" print("The given string is") print(str1) print("Checking if the first character is Capital or not") if (str1[0].isupper()): print("The first letter is a capital letter") else: print("The first letter is not a capital letter")

輸出

以上示例的輸出為:

The given string is
Welcome to Tutorialspoint
Checking if the first character is Capital or not
The first letter is a capital letter

示例 2

在下面給出的示例中,我們使用與上面相同的程式,但我們使用不同的輸入進行檢查。

str1 = "welcome to Tutorialspoint" print("The given string is") print(str1) print("Checking if the first character is Capital or not") if (str1[0].isupper()): print("The first letter is a capital letter") else: print("The first letter is not a capital letter")

輸出

以上示例的輸出為:

The given string is
welcome to Tutorialspoint
Checking if the first character is Capital or not
The first letter is not a capital letter

使用正則表示式

您可以使用 Python 中的正則表示式來測試字串是否以大寫字母開頭。要使用re庫,請匯入它,如果尚未安裝,請安裝它。

匯入 re 庫後,我們將使用正則表示式“子字串”。使用指定的正則表示式,re.search()函式檢查文字是否以大寫字母開頭。

示例 1

在下面給出的示例中,我們以字串作為輸入,並使用正則表示式檢查字串的第一個字母是大寫還是小寫。

import re str1 = "Welcome to Tutorialspoint" print("The given string is") print(str1) print("Checking if the first character is Capital or not") if re.search("^[A-Z]", str1): print("The first letter is a capital letter") else: print("The first letter is not a capital letter")

輸出

以上示例的輸出為:

The given string is
Welcome to Tutorialspoint
Checking if the first character is Capital or not
The first letter is a capital letter

示例 2

在下面給出的示例中,我們使用與上面相同的程式,但我們使用不同的輸入進行檢查。

import re str1 = "welcome to Tutorialspoint" print("The given string is") print(str1) print("Checking if the first character is Capital or not") if re.search("^[A-Z]", str1): print("The first letter is a capital letter") else: print("The first letter is not a capital letter")

輸出

以上示例的輸出為:

The given string is
welcome to Tutorialspoint
Checking if the first character is Capital or not
The first letter is not a capital letter

更新於: 2022年10月26日

14K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.