【问题标题】:.isalpha prints as False but when checked, is True.isalpha 打印为 False 但选中时为 True
【发布时间】:2016-12-06 14:52:29
【问题描述】:

这是用于检查密码是否为 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)        

【问题讨论】:

  • 在您的一些方法调用之后,您缺少()

标签: python passwords alphanumeric isalpha


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您必须使用if test1.isalpha() 而不是if test1.isalpha

    test1.isalpha 是一个方法,而test1.isalpha() 将返回结果TrueFalse。当您检查 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
    

    【讨论】:

      【解决方案3】:

      这样的事情怎么样?

      • len(test1)==9保证长度为9
      • hasNumbers(inputString) 函数在字符串中的任何数字上返回 char.isdigit()
      • re.match("^[A-Za-z0-9]*$", test1) 确保只有字母和数字使用 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!')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-27
        • 2019-04-24
        • 1970-01-01
        • 2020-09-30
        • 2012-10-08
        • 2015-07-17
        相关资源
        最近更新 更多