2016-12-06 29 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!')

相关问题