【问题标题】:How to single out a number and special character at the end of the password如何在密码末尾挑出数字和特殊字符
【发布时间】:2020-01-23 22:49:56
【问题描述】:

编写一个程序,要求用户输入密码(提示“密码:”)。然后它应该奖励用户“恭喜,你进来了!”如果密码长度介于 8 到 20 个字符之间(含),以数字结尾,并且包含句点或逗号。否则,它应该说“错!此事件将被报告!”

我需要能够在末尾有一个数字并包含句点或逗号。我不确定如何隔离密码的这两个部分。我该怎么做才能让用户输入密码?

user_pass = str(input())

if (len(user_pass <= 8) and (len(user_pass >= 20)) and  
    print ("Congratulations, you're in!")
else: 
    print ('Wrong! This incident will be reported!')

【问题讨论】:

标签: python


【解决方案1】:

只需使用and 添加更多条件。

Python 3:

password = input("Password: ")

if (8 <= len(password) <= 20) and password[-1].isdecimal() and any(x in password for x in {'.', ','}):
    print("Congratulations, you're in!")
else:
    print("Wrong! This incident will be reported!")

Python 2:

password = raw_input("Password: ")

if (8 <= len(password) <= 20) and unicode(password[-1]).isdecimal() and any(x in password for x in {'.', ','}):
    print("Congratulations, you're in!")
else:
    print("Wrong! This incident will be reported!")

【讨论】:

  • 我试过这段代码,但它给了我这个错误,我不知道如何解决它,为什么还要给这篇文章投反对票?我刚刚开设了一个新的 CS 专业帐户,所以我还在学习。预期输出以密码结尾:<_>
  • 它在 zybooks 上,所以它不会像我看到的那样让我在这里复制和粘贴它,但它告诉我我需要密码:然后输入,然后它会显示祝贺你喜欢它应该是。
  • @safarihunter,可能你使用的是python 2,我已经为这个版本添加了代码
  • @safarihunter,如果你能accept 回答你认为最好的,那就太好了。
【解决方案2】:

提示:

def password_is_good(password):
  return (
    password_length_is_correct(password) and
    password_ends_with_digit(password) and
    password_contains_punctuation(password)
  )

def password_length_is_correct(password):
  # implement this, and the rest.

password = str(input())
if password_is_good(password):
  # do something.
else:
  # do something else.

您可以通过索引访问字符串元素,负索引从末尾开始计数;例如password[-1] 将访问最后一个字符。

您可以使用in 运算符来检查字符串中是否存在字符,例如if 'c' in 'abcdef'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多