如何使 .isalnum() 方法仅对特定特殊字符返回 True?

我正在编写一个具有多个属性的密码分析器,其中之一是用户的密码不得包含特殊字符(@#$%^& *),除了!(感叹号)和_(下划线)。我正在使用该.isalnum()方法来实现此目的,但我无法找到一种方法来实现它,因此它不会返回 True !或_与任何其他特殊字符一起使用(例如:Python$返回 False 但Python_返回 True)。这是我的代码:


password = input('Enter a password: ')

if not password.isalnum():

    if '_' in password or '!' in password:

        pass

    else:

        print('Your password must not include any special characters or symbols!')


婷婷同学_
浏览 109回答 4
4回答

暮色呼如

最直观的方法就是检查每个字符。if not all(c.isalnum() or c in '_!' for c in password):     print('Your password must not include any special characters or symbols!')

跃然一笑

这是一种方法。!将和替换_为空字符串,然后用 进行检查isalnum()。password = input('Enter a password: ')pwd = password.replace('_', '').replace('!', '')if pwd.isalnum() and ('_' in password or '!' in password):    passelse:    print('Your password must not include any special characters or symbols!')

月关宝盒

检查它的另一种方法是使用正则表达式import rex = input('Enter a password: ')t = re.fullmatch('[A-Za-z0-9_!]+', x)if not t:    print('Your password must not include any special characters or symbols!')  

幕布斯7119047

def is_pass_ok(password):    if password.replace('_', '').replace('!','').isalnum():        return True    return Falsepassword = input('Enter a password: ')if not is_pass_ok(password):    print('Your password must not include any special characters or symbols!')通过删除所有允许的特殊字符,即_和!:password.replace('_', '').replace('!','')它仅检查字母数字字符 ( .isalnum())。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python