In Python, is there a way to validate a user input in a certain format? [duplicate]

我的未来我决定 提交于 2019-12-01 09:34:59

The standard (and language-agnostic) way of doing that is by using regular expressions:

import re

re.match('^[0-9]{2}-[0-9]{3}$', some_text)

The above example returns True (in fact, a "truthy" return value, but you can pretend it's True) if the text contains 2 digits, a hyphen and 3 other digits. Here is the regex above broken down to its parts:

^     # marks the start of the string
[0-9] # any character between 0 and 9, basically one of 0123456789
{2}   # two times
-     # a hyphen
[0-9] # another character between 0 and 9
{3}   # three times
$     # end of string

I suggest you read more about regular expressions (or re, or regex, or regexp, however you want to name it), they're some kind of swiss army knife for a programmer.

In your case, you can use a regular expression:

import re
while True:
   inp = input() # raw_input in Python 2.x
   if re.match(r'[a-zA-Z0-9]{2}-[a-zA-Z0-9]{3}$', inp):
       return inp
   print('Invalid office code, please enter again:')

Note that in many other cases, you can simply try converting the input into your internal representation. For example, when the input is a number, the code should look like:

def readNumber():
    while True:
        try:
          return int(input()) # raw_input in Python 2.x
        except ValueError:
          pass
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!