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