2016-12-06 26 views
-1

這是用於檢查密碼長度爲9個字符,字母數字且至少包含1個數字的函數的一部分。理想情況下,我應該能夠使用第一條if語句,但很奇怪,它不會運行。我無法弄清楚爲什麼test1.isalpha在if語句中作爲'True'運行,但打印爲'False'。.isalpha打印爲False,但選中時爲True

test1 = 'abcd12345' 

if len(test1) == 9 and test1.isalnum and not(test1.isalpha) 
    print('This should work.') 



if len(test1) == 9 and test1.isalnum: 
    if (test1.isalpha): 
     print('test1 is', test1.isalpha()) 

>>>('test1 is', False)   
+1

在您的一些方法調用之後,您缺少'()'。 – khelwood

回答

0

你要做if test1.isalpha()代替if test1.isalpha

test1.isalpha是一種方法,而test1.isalpha()會返回一個結果TrueFalse。當你檢查條件方法是否總是滿足。另一個取決於結果。

看看有什麼不同。

In [13]: if test1.isalpha: 
    print 'test' 
else: 
    print 'in else' 
    ....:  
test 

In [14]: if test1.isalpha(): 
    print 'test' 
else: 
    print 'in else' 
    ....:  
in else 
1

在您若(if (test1.isalpha):)正在測試的方法實例,而不是這種方法的結果。

你必須使用if (test1.isalpha()):(括號內)

0

怎麼這樣呢?

  • len(test1)==9確保9
  • hasNumbers(inputString)功能長度字符串
  • re.match("^[A-Za-z0-9]*$", test1)在任何數字返回char.isdigit(),以確保只有使用α和數字python re/regular expression

import re test1 = 'abcd12345' def hasNumbers(inputString): return any(char.isdigit() for char in inputString) if re.match("^[A-Za-z0-9]*$", test1) and hasNumbers(test1) and len(test1) == 9: print('Huzzah!')

相關問題