如何在 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