python 2.7 用户名的最小值和最大值

标签 python python-2.7 input

我在使用这段代码时遇到了问题。我刚刚开始使用 Python 2.7 进行编程,我想获得一些帮助。

这是代码:

username=raw_input("Please give me a username")
def gebruikersnaam():
    username(len)

    if len(username) >= 8:
        print "Well done"
    elif len(username) <= 1:
        print "More characters please" #Please try again, input your username again.

用户名也必须由数字组成。如果字符数为 0,我希望用户再次输入用户名。 谢谢!

最佳答案

基础版

这可能是一个解决方案:

from __future__ import print_function

while True:
    username = raw_input("Please give me a username: ")
    if not any(c in username for c in '0123456789'):
        print("Username needs to contain at least one number.")
        continue
    if len(username) >= 8:
        print("Well done")
    elif len(username) <= 1:
        print("More characters please.")
        print("Please try again, input your username again.")
        continue
    break

while 循环中不断询问用户,直到得到你想要的结果。

这会检查用户名是否至少包含一位数字:

>>> any(c in 'abc' for c in '0123456789')
False
>>> any(c in 'abc1' for c in '0123456789')
True

这部分是所谓的生成器表达式:

>>> (c in 'abc' for c in '0123456789')
<generator object <genexpr> at 0x10aa339e8>

可视化其正在执行的操作的最简单方法是将其转换为列表:

>>> list((c in 'abc' for c in '0123456789'))
[False, False, False, False, False, False, False, False, False, False]
>>> list((c in 'abc1' for c in '0123456789'))
[False, True, False, False, False, False, False, False, False, False]

它让 c 遍历 0123456789 的所有元素,即它采用值 01、 ... 依次9,并检查该值是否包含在abc中。

如果任何元素为 true,内置 any 将返回 True:

Return True if any element of the iterable is true. If the iterable is empty, return False.

检查字符串中数字的另一种方法是使用正则表达式。模块 re 提供此功能:

import re

for value in ['abc', 'abc1']:
    if re.search(r'\d', value):
        print(value, 'contains at least one digit')
    else:
        print(value, 'contains no digit')

打印:

abc contains no digit
abc1 contains at least one digit

在函数中

您可以将此功能放入一个函数中(按照 OP 在评论中的要求):

def ask_user_name():
    while True:
        username = raw_input("Please give me a username: ")
        if not any(c in username for c in '0123456789'):
            print("Username needs to contain at least one number.")
            continue
        if len(username) >= 8:
            print("Well done")
        elif len(username) <= 1:
            print("More characters please.")
            print("Please try again, input your username again.")
            continue
        break
    return username

print(ask_user_name())

关于python 2.7 用户名的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34836961/

相关文章:

java - 使用 OK/DONE 按钮在 Android 上以编程方式显示键盘

java - 扫描仪输入数组排序

python - 清理通过多次 pickler.dump 调用保存的数据的干净方法

python - 我不明白 Jinja2 调用 block

python - 一个类可以继承__init__()函数吗? (Python)

python - 两个数组之间的按行比较

python-2.7 - BeautifulSoup, 'ResultSet' 对象没有属性 'find_all'

PHP 输入 GET 变量清理

从多个列表创建 Python Numpy 数组

python - Python 2.7.10 抓取网页时 Unicode 字符替换为问号