如何在 Python 中檢查字串是否至少包含一個字母和一個數字?
在這篇文章中,我們將瞭解如何在 Python 中檢查字串是否至少包含一個字母和一個數字。
第一種方法使用正則表示式。要使用它,請匯入 re 庫,如果尚未安裝,則安裝它。匯入 re 庫後,我們可以使用正則表示式('^(?=.*[0-9]$)(?=.*[a-zA-Z])'。如果字串包含除字母和數字以外的任何特殊字元,則將返回 False;否則,將返回 True。
在正則表示式中,?= 語法用於呼叫前瞻。前瞻透過從當前位置向前檢視字串,在提供的字串中發現匹配項。
示例 1
在下面給出的示例中,我們以字串作為輸入,並使用正則表示式查詢字串是否至少包含一個字母和一個數字−
import re
str1 = "Tutorialspoint@123"
print("The given string is ")
print(str1)
res = bool(re.match('^(?=.*[0-9]$)(?=.*[a-zA-Z])', str1))
print("Checking whether the given string contains at least one alphabet and one number")
print(res)
輸出
上面示例的輸出如下所示−
The given string is Tutorialspoint@123 Checking whether the given string contains at least one alphabet and one number True
示例 2
在下面給出的示例中,我們使用與上面相同的程式,但傳送不同的字串作為輸入−
import re
str1 = "Tutorialspoint!@#"
print("The given string is ")
print(str1)
res = bool(re.match('^(?=.*[0-9]$)(?=.*[a-zA-Z])', str1))
print("Checking whether the given string contains at least one alphabet and one number")
print(res)
輸出
以下是上述程式碼的輸出−
The given string is Tutorialspoint!@# Checking whether the given string contains at least one alphabet and one number False
使用 isalpha() 方法和 isdigit() 方法
第二種方法是單獨檢查每個字元,以確定它是字母、數字還是其他字元。在這種方法中,我們將使用isalpha() 方法檢查字母,並使用isdigit() 方法檢查數字。
示例 1
在下面給出的程式中,我們以字串作為輸入並對其進行迭代,並檢查是否存在至少一個字母和一個數字−
def checkString(str1):
letter_flag = False
number_flag = False
for i in str1:
if i.isalpha():
letter_flag = True
if i.isdigit():
number_flag = True
return letter_flag and number_flag
str1 = "Tutorialspoint123"
print("The given string is ")
print(str1)
res = checkString(str1)
print("Checking whether the given string contains at least one alphabet and one number")
print(res)
輸出
上面示例的輸出如下所示−
The given string is Tutorialspoint123 Checking whether the given string contains at least one alphabet and one number False
示例 2
在下面給出的示例中,我們使用與上面相同的程式,但傳送另一個字串作為輸入,並檢查它是否至少包含一個字母和一個數字−
def checkString(str1):
letter_flag = False
number_flag = False
for i in str1:
if i.isalpha():
letter_flag = True
if i.isdigit():
number_flag = True
return letter_flag and number_flag
str1 = "Tutorialspoint!@#"
print("The given string is ")
print(str1)
res = checkString(str1)
print("Checking whether the given string contains at least one alphabet and one number")
print(res)
輸出
以下程式的輸出為−
The given string is Tutorialspoint!@# Checking whether the given string contains at least one alphabet and one number False
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP