2

I want to validate a PAN card whose first 5 characters are alphabets, the next 4 are numbers and the last character is an alphabet again. I can't use isalnum() because I want to check this specific order too, not just verify whether it contains both numbers and letters.

Here is a snipped of my code:

def validate_PAN(pan):
    for i in pan:
        pan.isalpha(pan[0:4])==True:
            return 1
        pan.isdigit(pan[5:9])==True:
            return 1
        pan.isalpha(pan[9])==True:
            return 1
        else:
            return 0

This obviously returns an error since it is wrong. How can I fix this?

Ram
  • 4,724
  • 2
  • 14
  • 22

3 Answers3

3

Just do string slicing and check

s[:5].isalpha()

pan[0:4] - Here you check for the first 4 characters and not 5 characters.

s[m:n] - This will slice the string from mth character till nth character (not including n)

Mistake in your code

pan.isalpha(pan[0:4])==True

This is giving you the error because isalpha() doesn't accept any arguments and you aren't using if before it.

You must use - if pan[:5].isalpha() == True:

Ram
  • 4,724
  • 2
  • 14
  • 22
0

You can use regular expression for simplicity sake

import re

PAN_1 = 'ABCDE1111E'
PAN_2 = 'ABC1111DEF'

def is_valid_PAN(PAN_number):
    return bool(re.match(r'[a-z]{5}\d{4}[a-z]', PAN_number, re.IGNORECASE))

print(is_valid_PAN(PAN_1)) #True
print(is_valid_PAN(PAN_2)) #False
Epsi95
  • 8,832
  • 1
  • 16
  • 34
0

Regular expressions are a good fit for this.

import re

# Pattern for matching a PAN number
pattern = r'\b[A-Z]{5}[0-9]{4}[A-Z]\b'

# compile the pattern for better performance with repetitive matches
pobject = re.compile(pattern)

pan_number = "AXXMP1234Z"
result = pobject.match(pan_number)

if result:
    print ("Matched for PAN: ", res.group(0))
else:
    print("Failed")
Fractal
  • 816
  • 5
  • 15