2014-11-21 47 views
1
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 == 

這是我要問,如果密碼只包含數字,但我不知道該怎麼做,我使用AND和OR已經嘗試過,但悲慘地失敗了。檢查字符串包含只有一些價值觀,而不是別人

+3

對這類問題使用正則表達式。 – 2014-11-21 10:08:42

回答

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): 
+0

這是如何工作的? +1它在代碼中工作,只是想知道如何? – Razor 2014-11-21 10:15:08

+0

@Razor我添加了一個解釋。 – parchment 2014-11-21 10:18:42

+0

驚人的,簡單和簡單的解決方案。非常快! – Qmage 2015-11-19 11:06:52

5

使用isdigit()

>>> "abcd123".isdigit() 
False 

>>> "123".isdigit() 
True 
0

好,串只有當它可以轉換成int只有數字,所以......

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