【问题标题】:How to make the .isalnum() method return True for only specific special characters?如何使 .isalnum() 方法仅针对特定的特殊字符返回 True?
【发布时间】:2020-12-26 01:42:17
【问题描述】:

我正在编写具有多个属性的密码分析器,其中一个是用户的密码不能包含特殊字符 (@#$%^&*),! 除外(感叹号)和 _(下划线)。我为此目的使用了.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!')

【问题讨论】:

    标签: python


    【解决方案1】:

    这是一种方式。将!_ 替换为空字符串,然后使用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!')
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • OP 希望"Python$_" 正常。
      • @MarianD 不,除了_! 之外,他们不需要特殊字符。这个问题的措辞令人困惑。
      【解决方案3】:

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

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

      【讨论】:

      • 请注意,str.isalnum() 适用于所有 Unicode,但 [A-Za-z0-9] 仅适用于 ASCII。 \w 更接近(包括下划线),但我不确定它是否等效。
      【解决方案4】:
      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())。

      【讨论】:

      • 这将有助于解释这段代码的工作原理。一两句话就可以了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 2014-11-03
      相关资源
      最近更新 更多