如何限制python输入的字符类型

2024-04-20 12:03:50 发布

您现在位置:Python中文网/ 问答频道 /正文

如何限制可以输入的字符数和字符类型。你知道吗

s = input('What is your number)

一个数字只能是9位数,所以应该限制为9位数,并且只能是数字

x = input('what is your email address)

电子邮件地址至少可以包含8个字符,最多可以包含60个字符,并且必须包含@符号。你知道吗

我该怎么做呢?你知道吗


Tags: 类型numberinputyourisaddress电子邮件email
1条回答
网友
1楼 · 发布于 2024-04-20 12:03:50

事实上,我亲爱的朋友,你不能限制输入功能,但你可以通过这种方式实现你想要的:

def isnumber(s):
    if s.isdigit() and len(s) <= 9:
        return True
    else:
        print('you should input number and length less than 9')
        return False

def main():
    s = input('What is your number')
    while not isnumber(s):
        s = input('What is your number')
    print("your number is", s)


if __name__ == "__main__":
    main()

相关问题 更多 >