Python Practice › Function Programs › Program 37
Validate a mobile number
Write a Python function to check whether a mobile number is valid: 10 digits starting with 6, 7, 8 or 9 (optionally with +91).
Input
"9876543210", "+91 9123456789", "12345"
Output
9876543210 True +91 9123456789 True 12345 False 5876543210 False
Approach
- A regular expression describes the pattern.
Solution
import re def is_valid_mobile(number): return bool(re.fullmatch(r"(\+91[\s-]?)?[6-9]\d{9}", number.strip())) for n in ["9876543210", "+91 9123456789", "12345", "5876543210"]: print(n, is_valid_mobile(n))Output
9876543210 True +91 9123456789 True 12345 False 5876543210 False
Line by line
Line 4
fullmatch requires the whole string to fit, so extra characters fail.
Learn the concept
New to this topic? Read the lesson, then come back.