4

While preparing for my AS-Level Computer Science exam I came across a question in the pre-release material:

Prompt the user to input a User ID and check if the format of the ID corresponds with pre-defined formatting rules and output accordingly.

The Format (In order):

  1. One upper case letter
  2. Two Lower case letters
  3. Three numeric characters (digits)

Example: "Abc123"

I came up with a solution using my language of choice(Python), however, I was wondering if there is a more elegant or better way to solve this. Especially the third check.

Here is my code:

#Task 2.2

u_id = input("Input User ID: ") #DECLARE u_id : string
numbers = [str(num) for num in range(10)]

#Checking if final 3 characters of User ID (u_id) are digits
for i in list(u_id[3::]):
    if i not in numbers:
        digit_check = False #DECLARE digit_check : bool
        break
    else:
        digit_check = True

#User ID format check
if (u_id[0:1].isupper() == True) and (u_id[1:3] == u_id[1:3].lower()) and (digit_check == True):
    print ("Correct Format")
else:
    print ("Wrong Format")

Ignore the DECLARATION comments. They are an exam requirement.

Thanks

6
  • 3
    Much easier/cleaner with regexp /([A-Z])([a-z]{3})([0-9]{3})/ (something like that, it's been a while) Commented Feb 28, 2016 at 18:36
  • Given that you don't have a specific problem, this is perhaps not a great question for stackoverflow. There are probably better sites on the stack exchange network (maybe programmers?) for this question. Commented Feb 28, 2016 at 18:38
  • 1
    Learn about regular expressions. They are really useful for this kind of tasks. Commented Feb 28, 2016 at 18:41
  • 2
    print('Correct Format' if re.match(r'[A-Z][a-z]{2}[0-9]{3}', u_id) else 'Wrong Format') should do it. Commented Feb 28, 2016 at 18:41
  • @JCOC611 Thanks, I'll look into it. Haven't learnt regexp yet. Commented Feb 28, 2016 at 18:41

2 Answers 2

13

If you are allowed to import re:

import re

u_id = input("Input User ID: ") #DECLARE u_id : string

rex = re.compile("^[A-Z][a-z]{2}[0-9]{3}$")
if rex.match(u_id):
    print("Correct format")
else:
    print("Incorrect")

Explanation of expression:

  • ^ represents the beginning of a string.
  • [A-Z] is a range, containing all uppercase letters (in the English alphabet).
  • [a-z] is a range, containing all lowercase letters.
  • [0-9] is a range, containing all numbers.
  • {n} specifies that n items (items are whatever is before the curly brackets) will be matched.
  • $ represents the end of the string.

Also, you can see more detailed explanations and test arbitrary strings against this regular expression here.

Sign up to request clarification or add additional context in comments.

2 Comments

Only 2 lower case characters, plus you don't really need need to group them (). Good idea on the $, so you probably should have the start ^ too.
Lol I think it should be fine now. @AChampion thanks for the recommendations!
2

If you want to solve it without regular expressions (mind you, in this case they are the right tool!), you could do something like this:

id_format = [
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ", # or string.ascii_uppercase etc.
    "abcdefghijklmnopqrstuvwxyz",
    "abcdefghijklmnopqrstuvwxyz",
    "0123456789",
    "0123456789",
    "0123456789",
]

def check(input):
    # check for same length
    if len(input) != len(id_format):
        return False

    for test, valid in zip(input, id_format): # itertools.zip_longest can make
        if test not in valid:                 # the length check unnecessary
            return False       

    return True

check("Abc123") # True
check("abc123") # False

5 Comments

return all(test in valid for test, valid in zip(input, id_format) would also work.
Good one for interview
You could also provide functions instead of strings (i.e str.isupper, str.islower, str.isdigit...) which could be more efficient.
@AChampion: That's beautiful!
@JCO611: I agree. I tried to create the clearest code possible, your regex solution is of course the "correct" one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.