Welcome to our comprehensive guide on Python Phone Number Validation! In this tutorial, we will learn how to create a script that checks the validity of a phone number. This is a practical and useful skill, especially for web development projects. Let's get started!
Validating phone numbers is essential for several reasons:
Before we dive into the code, let's discuss common phone number formats:
Where XX represents the country code, and XXXX represents the local number.
Now, let's create a simple phone number validation script using Python.
def validate_phone_number(number):
# Remove non-digit characters
number = re.sub(r'\D', '', number)
# Check if the number has the correct length
if len(number) < 10 or len(number) > 15:
return False
# Check if the number follows a specific pattern
if len(number) == 10 and number[0] == '1':
# US format
if len(number) == 11 and number[1:3] in ['2', '3', '4', '5', '6', '7', '8', '9']:
# Area code
if number[3:6] in ['2', '3', '4', '5', '6', '7', '8', '9']:
# Local number
if number[6:] in ['2', '3', '4', '5', '6', '7', '8', '9']:
return True
elif len(number) == 11 and number[0] == '0' and number[1] == '1':
# UK format
if number[2:] in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
return True
elif len(number) == 12 and number[0] == '0' and number[1] == '4' and number[2] == '4':
# International format
if number[3:] in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
return True
return False
# Test the function
number = '1234567890'
if validate_phone_number(number):
print('The phone number is valid.')
else:
print('The phone number is not valid.')In the code above, we define a validate_phone_number function that checks the validity of a phone number. The function removes non-digit characters, checks the length, and verifies if the number follows a specific pattern for US, UK, and international formats.
Don't forget to import the re module at the beginning of your script:
import reWhat is the first step in our phone number validation script?
Now that you've learned how to create a phone number validation script, you can apply this skill to various real-world projects. Happy coding! 🚀