-1

这是用于检查密码是否为 9 个字符长、字母数字且包含至少 1 个数字的函数的一部分。理想情况下,我应该能够使用第一个 if 语句,但奇怪的是,它没有运行。我无法弄清楚为什么 test1.isalpha 在 if 语句中运行为“真”但打印为“假”。

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)        
4

3 回答 3

1

在您的 if ( if (test1.isalpha):) 中,您正在测试方法实例,而不是该方法的结果。

你必须使用if (test1.isalpha()):(括号)

于 2016-12-06T14:56:46.483 回答
0

你必须做if test1.isalpha()而不是if test1.isalpha

test1.isalpha是一个方法,并且test1.isalpha()会返回一个结果Trueor False。当您检查 if 条件方法时,将始终满足。另一个取决于结果。

看差距。

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
于 2016-12-06T14:56:23.120 回答
0

这样的事情怎么样?

  • len(test1)==9确保长度为 9
  • hasNumbers(inputString)函数返回char.isdigit()字符串中的任何数字
  • re.match("^[A-Za-z0-9]*$", test1)使用python re /正则表达式确保只有字母和数字

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!')

于 2016-12-06T15:27:08.293 回答