Python 3 : String validation (password)

标签 python python-3.x

这些语句单独工作(我已经制作了单独的辅助函数),并且我已将它们编译到一个函数中。我怎样才能让他们一起工作?另外,我如何让这个程序在没有模块“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

最佳答案

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

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

(1) 嵌套 ifs

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's laws )。

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

关于Python 3 : String validation (password),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50246488/

相关文章:

python - SQLAlchemy,声明式,PostgreSQL : cannot create tables

python - 如何将列表导出到 Excel 兼容文件中?

python - Sphinx 找不到我的 python 文件。说 'no module named ...'

python-3.x - 如何定期更新日期时间?

python-3.x - 如何绘制多类数据的 ROC 曲线并从混淆矩阵测量 MAUC

python - Python 中 R 的 seq_len 等价物

python - 使用 zipfile 读取受密码保护的 Word 文档

python - 先决条件的简单比较不起作用

python - 将列表转换为矩阵

python - 如何在 Python 中使用 sys.exit()