Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Format Checking in Python

Tags:

python

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

like image 596
Hassan.S Avatar asked Dec 08 '22 23:12

Hassan.S


1 Answers

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.

like image 176
JCOC611 Avatar answered Dec 29 '22 02:12

JCOC611