【问题标题】:Can't forbid numbers from a username that includes alphabetical characters不能禁止用户名中包含字母字符的数字
【发布时间】:2020-09-19 22:04:45
【问题描述】:

我正在尝试编写一个代码来禁止新用户在其用户名中写入数字。

到目前为止,我一直在写这篇文章:

all_users = ['andrew', 'carolina', 'david']
new_user = "please provide a username"
if new_user.isnumeric():
       print(f"the username {new_user} is unavailable, please don't use numbers.")
elif new_user not in all_users:
       print(f"{new_user.title()}, welcome to the game!")

问题是在我尝试将字母字符与数字混合之前,代码工作得很好。我似乎无法找到一种方法来告诉 Python 禁止同时包含数字和普通字符的用户名。

提前感谢您的任何建议:)

【问题讨论】:

  • .isalpha() 返回真,如果字符串只包含字母(也包括各种语言的 unicode 字母)

标签: python list numbers


【解决方案1】:

isnumeric() 如果整个字符串是数字,则返回 true。您想知道是否有任何字符是数字。

any(x.isnumeric() for x in new_user)

【讨论】:

    【解决方案2】:

    你应该使用正则表达式https://docs.python.org/fr/3/howto/regex.html

    或者简单地测试任何字符是否为数字

    ...
    
    if any(char.isnumeric() for char in new_user):
        print(f"the username {new_user} is unavailable, please don't use numbers.")
    ...
    

    【讨论】:

      【解决方案3】:

      如果您只想接受字母字符,请检查用户名是否只有字母字符。数字不是唯一的非字母字符。

      all_users = ['andrew', 'carolina', 'david']
      new_user = "please provide a username"
      if not new_user.isalpha():
         print(f"the username {new_user} is unavailable, please don't use non-alphabetic characters.")
      elif new_user not in all_users:
         print(f"{new_user.title()}, welcome to the game!")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-26
        • 2021-08-29
        • 2013-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-15
        • 2011-01-24
        相关资源
        最近更新 更多