Python检查字符串是否包含任何数字

本文概述

给定一个字符串, 检查它是否包含任何数字。

输入:test_str =‘geeks4g2eeks’
输出:True
说明:
包含4和2
入:test_str =‘srcmini’
输出:False
说明:不包含数字。

方法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))

输出如下

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

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


来源:

https://www.srcmini02.com/70499.html

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?