为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

婷婷同学_ 2023-07-18 16:27:35
我正在编写一个具有多个属性的密码分析器,其中之一是用户的密码不得包含特殊字符(@#$%^& *),除了!(感叹号)和_(下划线)。我正在使用该.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!')
查看完整描述

4 回答

?
暮色呼如

TA贡献1853条经验 获得超9个赞

最直观的方法就是检查每个字符。

if not all(c.isalnum() or c in '_!' for c in password):
    print('Your password must not include any special characters or symbols!')


查看完整回答
反对 回复 2023-07-18
?
跃然一笑

TA贡献1826条经验 获得超6个赞

这是一种方法。!将和替换_为空字符串,然后用 进行检查isalnum()。


password = input('Enter a password: ')

pwd = password.replace('_', '').replace('!', '')

if pwd.isalnum() and ('_' in password or '!' in password):

    pass

else:

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


查看完整回答
反对 回复 2023-07-18
?
月关宝盒

TA贡献1772条经验 获得超5个赞

检查它的另一种方法是使用正则表达式


import re

x = 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!')  


查看完整回答
反对 回复 2023-07-18
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

def is_pass_ok(password):

    if password.replace('_', '').replace('!','').isalnum():

        return True

    return False



password = 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())。


查看完整回答
反对 回复 2023-07-18
  • 4 回答
  • 0 关注
  • 107 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信