Python:输入验证字符串长度 [英] Python: Input validate with string length
本文介绍了Python:输入验证字符串长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好,所以我需要确保电话号码长度正确.我想到了这一点,但遇到语法错误.
Ok so i need to ensure that a phone number length is correct. I came up with this but get a syntax error.
phone = int(input("Please enter the customer's Phone Number."))
if len(str(phone)) == 11:
else: phone = int(input("Please enter the customer's Phone Number."))
phonumber.append(phone)
推荐答案
您可以尝试使用它来询问电话号码,直到正确为止:
You may try this to be asking for the phone number until it is correct:
phone = ""
while len(str(phone)) != 11:
phone = int(input("Please enter the customer's Phone Number."))
phonumber.append(phone)
如果您还想检查输入内容是数字而不是文本,那么在这种情况下,还应该捕获int
引发的异常,例如:
If you want to check also that the input is a number and not text, you should also trap the exception raised by int
in that case, for example:
phone = ""
while len(str(phone)) != 11:
try:
phone = int(input("Please enter the customer's Phone Number."))
except ValueError:
phone = ""
phonumber.append(phone)
这篇关于Python:输入验证字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文