Python – 检查字符串是否包含任何数字
给定一个字符串,检查它是否包含任何数字。
Input : test_str = ‘geeks4g2eeks’
Output : True
Explanation : Contains 4 and 2.
Input : test_str = ‘geeksforgeeks’
Output : False
Explanation : Contains no number.
方法 #1:使用 any() + isdigit()
上述功能的组合可以用来解决这个问题。在此,我们使用 isdigit() 检查数字并使用 any() 检查是否出现任何事件。
Python3
# Python3 code to demonstrate working of
# Check if string contains any number
# Using isdigit() + any()
# initializing string
test_str = 'geeks4geeks'
# printing original string
print("The original string is : " + str(test_str))
# using any() to check for any occurrence
res = any(chr.isdigit() for chr in test_str)
# printing result
print("Does string contain any digit ? : " + str(res))
Python3
# Python3 code to demonstrate working of
# Check if string contains any number
# Using isdigit() + next() + generator expression
# initializing string
test_str = 'geeks4geeks'
# printing original string
print("The original string is : " + str(test_str))
# next() checking for each element, reaches end, if no element found as digit
res = True if next((chr for chr in test_str if chr.isdigit()), None) else False
# printing result
print("Does string contain any digit ? : " + str(res))
输出
The original string is : geeks4geeks
Does string contain any digit ? : True
方法 #2:使用 next() + 生成器表达式 + isdigit()
这是可以执行此任务的另一种方式。建议在较大字符串的情况下这样做,生成器中的迭代很便宜,但构造通常效率低下。
Python3
# Python3 code to demonstrate working of
# Check if string contains any number
# Using isdigit() + next() + generator expression
# initializing string
test_str = 'geeks4geeks'
# printing original string
print("The original string is : " + str(test_str))
# next() checking for each element, reaches end, if no element found as digit
res = True if next((chr for chr in test_str if chr.isdigit()), None) else False
# printing result
print("Does string contain any digit ? : " + str(res))
输出
The original string is : geeks4geeks
Does string contain any digit ? : True