[英]Python check if a input has a digit in it?
Im trying to see how i can see if a number is in a users input. 我试图看看我是如何看到一个数字是否在用户输入中。 i tried using .isdigit()
but only works if its just a number. 我尝试使用.isdigit()
但只有它只是一个数字。 im trying to add it to a password checker. 我试图将其添加到密码检查器。 i also tried .isalpha()
but didn't work. 我也试过.isalpha()
但没有奏效。 what have i done wrong and what do i need to add or change? 我做错了什么,我需要添加或更改什么?
here is what i have 这就是我所拥有的
password = input('Please type a password ')
str = password
if str.isdigit() == True:
print('password has a number and letters!')
else:
print('You must include a number!')`
You can use a generator expression and an isdigit()
within the any
function : 您可以在any
函数中使用生成器表达式和isdigit()
:
if any(i.isdigit() for i in password) :
#do stuff
The advantage of using any
is that it doesn't traverse the whole string and will return a bool value if it finds a digit for the first time! 使用any
的优点是它不会遍历整个字符串,如果第一次找到一个数字,它将返回一个bool值!
It is equal to the fallowing function : 它等于休假功能:
def any(iterable):
for element in iterable:
if element:
return True
return False
You may try re.search
你可以试试re.search
if re.search(r'\d', password):
print("Digit Found")
And don't use builtin data types as varible names. 并且不要将内置数据类型用作可变名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.