Phone number search using Python | applied electronics engineering

Latest

Phone number search using Python

By Applied Electronics - Saturday, July 2, 2016 No Comments

Python programming language is excellent programming language for searching text strings. Consider a basic example where you want to search for phone numbers which has the following form- NNN-NNN-NNNN, where N is a number, for example- 342-934-2334.

We can use simple language construct to search for this particular number or we can use regular expression. Here we show how to search using the simple language construct.

For this purpose, we let user to enter a text string. Then we create a search function and let's call it searchph( ). This function checks whether a entered text string matches out phone number pattern. The function returns either True or False. If the return is True then we print out message that the entered string is a phone number otherwise we print that it is not a valid phone number

Program Code:

Below is the program code to do this.

text = input('Enter Phone Number to be searched: ')

def searchph(text):
        if len(text) != 12:
            return False
        for c in range(0,2):
            if not text[c].isdecimal():
                return False
        if text[3] != '-':
            return False
        for c in range(4,6):
            if not text[c].isdecimal():
                return False
        if text[7] != '-':
            return False
        for c in range(8,11):
            if not text[c].isdecimal():
                return False
        return True
       
       
if searchph(text) == True:
    print("It is a phone number")
else:
    print("It is not a phone number")

Program File:

The above program is saved as searchph.py file. The file is run in Spyder IDE.

Output:

The following are outputs from this program:

runfile('D:/python/proj1/searchph.py', wdir='D:/python/proj1')

Enter Phone Number to be searched: asdf
Not Found

runfile('D:/python/proj1/searchph.py', wdir='D:/python/proj1')

Enter Phone Number to be searched: 342-934-2334
It is a phone number




Tags:

No Comment to " Phone number search using Python "