4

In python, I'm asking the user to input an office code location which needs to be in the format: XX-XXX (where the X's would be letters)

How can I ensure that their input follows the format, and if it doesn't ask them to input the office code again?

Thanks!

user1186420
  • 127
  • 1
  • 2
  • 5

2 Answers2

8

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.

Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
  • Thanks, so if I needed it to be letters would I just use re.match('^[A-Z]{2}-[A-Z]{3}$', some_text) – user1186420 Apr 01 '12 at 15:57
  • 1
    if you only want uppercase letters, yes. If you also want lowercase letters you can use `[A-Za-z]`, or pass the [`IGNORECASE`](http://docs.python.org/library/re.html#re.IGNORECASE") flag. – Gabi Purcaru Apr 01 '12 at 15:59
3

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
phihag
  • 278,196
  • 72
  • 453
  • 469