检查字符串是否仅包含某些值,而不包含其他值

时间:2014-11-21 10:04:59

标签: python

print("Hello, welcome to password strength. Test how strong your password is todai!")
password = input("Well enter a password why don't you... ")
print("So your password is", password)
print("Well ok, let's see what i can understand from this...")

if len(password) < 6:   
    print("Your password is too short")    
else:    
    print("Your password is of a good length")    

if password == password.upper():    
    print("Your password has too many uppercase letters")
else:    
    print("Your password has 0 or a couple upper case letters, please consider making your password remember-able.")

if password == password.lower():    
    print("Your password needs a upper case letter case letters")
else:    
    print("Your password has a suitable amount of lowercase vs upper case letters")

if password == 

这是我想询问密码是否仅包含数字的地方,但我不知道如何做到这一点,我已经尝试过使用ands和ors,但却失败了。

3 个答案:

答案 0 :(得分:5)

使用isdigit()

>>> "abcd123".isdigit()
False

>>> "123".isdigit()
True

答案 1 :(得分:1)

你可以这样做:

if set(password) <= set('1234567890'):

这会询问密码中的字符集是否是所有数字字符集的子集。

set是无序的值集合,无法复制。一些例子:

>>> set('swordfish')
{'d', 'f', 'h', 'i', 'o', 'r', 's', 'w'}

>>> set('aaaaassssdddfff')
{'a', 'd', 'f', 's'}

>>> set('1234')
{'1', '2', '3', '4'}

集有几个有用的函数,例如检查子集:

>>> set('1234') <= set('1234567890')
True

>>> set('a1234') <= set('1234567890')
False

这可以很容易地扩展到测试其他内容,例如,如果密码只包含标点符号:

from string import punctuation

if set(password) <= set(punctuation):

或仅限字母数字字符:

from string import ascii_letters, digits

if set(password) <= set(ascii_letters + digits):

答案 2 :(得分:0)

嗯,字符串只有在可以转换为int时才有数字,所以......

try:
    int(password)
except ValueError:
    print("not parseable to int, so not only numbers")
else:
    print("Only numbers")