2

How do i do an input validation for NRIC numbers where there are both numbers and alphabets? Example of NRIC number: S9738275G, S8937231H, S7402343B ic=input('Enter NRIC Number: ')

3

3 Answers 3

1

For your use case this should be enough:

>>> a = 'A12345678B'
>>> if a[0].isalpha() and a[-1].isalpha() and a[1:-1].isdigit(): print True
... 
True
>>> a = 'A12345678'
>>> if a[0].isalpha() and a[-1].isalpha() and a[1:-1].isdigit(): print True
... 
>>> 

[0] first character, [-1] last character, [1:-1] second character to last but one character

Edit: Looking at PM 2Ring's comment, the NRIC number has a specific structure and specific method of creating the check digit/character, so I'd follow the code given in the link provided. Assuming that your NRIC number is the same obviously, as you didn't specify what it was.
Intriguingly: "The algorithm to calculate the checksum of the NRIC is not publicly available" Wikipedia

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

2 Comments

You could use .isdigit, then you wouldn't need the try:... except.
@PM2Ring Absolutely true but when I tested it I forgot the () in isdigit() and used int() instead. Only after I posted did a realise my typo.
0

This can be done in a lot of different ways. Depending on the scale of your application, you might want something simpler or more complex.

If you want something rock solid, you can use a library such as Pygood for that.

If you're looking for something in the middle, you can also use regex, see here an example.

If you want to keep it as simple as possible, you can do a simple validation like so:

str = "B123"
if str[0].isalpha() and not str[1:].isalpha():
    # is valid

1 Comment

How about the number of alphabets and numerics needed to input? In this case it would be 9 as ' S9738275G' has 9 alphanumeric.
0

Try this

string = 'S9738275G';

if string.isalnum():
    print('It\'s alphanumeric string')
else:
    print('It\'s not an alphanumeric string')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.