Python 3:字符串验证(密码)

学科

这些语句单独起作用(我已经制作了单个辅助函数),并将它们编译为一个函数。我如何使他们一起工作?另外,如何使该程序在没有模块“ re”的情况下运行?它可以工作,但我在此站点上得到别人的帮助。这些是我在此程序中需要的:

  • 必须有一个号码
  • 字符串开头和结尾的字符必须是字母
  • 必须介于10到20个字符之间
  • 连续不能有3个字符
  • 以前的密码无法再次使用

这是我的代码:

import re 
def password_validator (pw_v, prev_p): #pw_v = string that is to be validated; prev_p = previously used strings in a list

    prev_P = [s]
    # do I use 'while True' instead of returning True statements every time?
    if 10 <= len(s) <=20:
        return True
    elif s[0] and s[-1].isalpha():
        return True 
    elif not re.search('(.)\\1{2}', s): # How else can I write this without using 're'?
        return True
    elif any(digit.isdigit() for digit in s):
        return True
    else: 
        return False
加拉布拉

您的代码检查输入是否仅满足条件之一。

请注意,当您使用时return,该函数将返回并忽略其余代码。考虑到这一事实,您可以使用以下任一方法:

(1)嵌套if

if 10 <= len(s) <= 20:
    if s[0] and s[-1].isalpha():
        # the rest of the conditions
            return True    # all of the conditions were met
return False    # one of the conditions wasn’t met

(2)false当不满足第一个条件时返回(实际上使用De Morgan定律)。

if not 10 <= len(s) <= 20:
    return False
if not s[0] and s[-1].isalpha():
    return False 
# the rest of the conditions

关于正则表达式的使用,我认为在这种情况下是优雅的。但您始终可以切换到一个循环,该循环遍历输入的字符,再加上一个重复字符的计数器(效果不佳):

def three_identical_characters(input):
    counter = 0
    for i in range(1, len(input)):
        counter += (1 if (input[i] == input[i-1]) else 0)
        if counter == 2:
            return True
    return False

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章