如何在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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP