首页 > 解决方案 > 如何制作一个检测缺失字符串的程序

问题描述

我希望用户使用 input() 函数创建密码。如果用户密码少于 8 个字符或不包含感叹号,则打印“您的密码不符合我们的要求”。</p>

我有这个:

password = input("Create a password")
if len(password)<8: 
  print("Your password doesn't meet the requirements")
if("!" not in password.title()):
  print("Your password doesn't meet the requirements")

我使用 .title() 因为这是我迄今为止所学到的。大概是不正确的。

标签: pythonpython-3.x

解决方案


如果您想使用单独的 if 语句检查这两个条件,请进一步缩进最后两行,这正是您想要的

但是,您可以同时检查这两个条件(并且没有必要将字符串大写来检查特殊字符或长度)

if len(password)<8 or "!" not in password:
  print("Your password doesn't meet the requirements") 

如果您想要更复杂/更精确的密码(仅限字母数字、特殊字符等),请使用正则表达式


推荐阅读