Python 3 - 在字符串中查找至少2个数字

时间:2015-05-27 04:30:28

标签: python string python-3.x numbers digits

我需要在程序中获取用户创建的密码。密码长度应为6~10个字符,并且包含至少2个数字

我可以处理长度,但我不知道如何确保字符串中有2个数字。我曾尝试使用isdigit,但它只会告诉我字符串中是否有数字。

如何验证字符串中至少有2位数?

4 个答案:

答案 0 :(得分:3)

这是查找字符串中数字位数的一种方法:

>>> pw = 'fgfg57gfgf7'
>>> sum(1 for x in pw if x.isdigit())
3

说明

此:

(1 for x in pw if x.isdigit())

是一个生成器表达式。将其转换为列表会显示其内容:

>>> list((1 for x in pw if x.isdigit()))
[1, 1, 1]

这相当于:

res = []
for x in pw:
    if x.isdigit():
        res.append(1)

总结这些数字会给你一个数字位数。

由于您不需要列表但只需要数字的总和, 生成器表达式通常更好。它避免了构建不需要的东西 列表。

更新

正如@ TigerhawkT3所说,这也有效:

>>> sum(x.isdigit() for x in pw)  
3

因为它给出了这个结果:

>>> list(x.isdigit() for x in pw)
[False, False, False, False, True, True, False, False, False, False, True]  

FalseTrue属于bool类型,其继承自int,意思是 您可以将False视为0,将True视为1

答案 1 :(得分:2)

这依赖于onPlay()/onPause()的值为True1的值为False的事实。

0

这是另一种拼写相同想法的方法:

if sum(map(str.isdigit, password)) >= 2:

答案 2 :(得分:0)

您可以尝试以下re.search命令。

if re.search(r'\d.*?\d', password):

仅当密码包含至少两位数字时才会进入if条件。

示例:

>>> import re
>>> password = 'foo1b2'
>>> if re.search(r'\d.*?\d', password):
        print("Two digits found")

Two digits found
>>> password = 'foo1bf'
>>> if re.search(r'\d.*?\d', password):
        print("Two digits found")


>>> 

答案 3 :(得分:0)

password = "sd909sdj23"
counter=0
for ch in password:
    if(ch.isdigit()):
        counter+=1
if (counter<2):
    //Alarm the user here