Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 984
user1186420 Avatar asked Dec 22 '22 00:12

user1186420


1 Answers

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.

like image 127
Gabi Purcaru Avatar answered Mar 29 '23 22:03

Gabi Purcaru