Home »
Python »
Python Programs
Extract the mobile number from the given string in Python
Here, we will learn how to extract the mobile/phone number from a given string by using the re module in the Python programming language?
Submitted by Bipin Kumar, on November 28, 2019
Extract the mobile number from the given string
To solve this problem easily, we will use the re module in the program. A string will be given by the user and we have to extract the mobile number by using the Python programming language. Before going to use the re module, we will learn a little bit about re module.
Python has an inbuilt re module which allows us to solve the various problems based on pattern matching and string manipulation. The re module or regex is an abbreviated form of the regular expression. This module of Python in our daily life is very useful, by using re module you can find the contact number, email-id, special pattern, etc from a file or given sentences. The re module provides a lot of metacharacters and to solve the problem we will use the \d which is used to match any decimal digits(0-9) in the given string or sentence.
Example
Let's take an example to understand the problem better,
Input:
"Hello! I am bipin Kumar and my contact number is 918481234422.
May i know the call logs of my number"
Output:
918481234422
Explanation:
The program will have to find a substring that contains
12 digit substring and print it.
Algorithm
Algorithm to solve the above problem
- Initially, we will import the re module in the program.
- Assign the given string or sentence in a variable.
- As we all know the contact number or mobile will be of 12 digits that why we will form a format that will use to extract the mobile number.
- Now, print the extracted number.
Program
# importing the module
import re
# string
string='''If you would like to get in touch with us through other ways,
the Flipkart customer support number is 018002089898.
And we're just a call away if you need anything.
You can also arrange a call-back from within the
Flipkart app regarding any issue related to your order.'''
# extracting the mobile number
Phonenumber=re.compile(r'\d\d\d\d\d\d\d\d\d\d\d\d')
m=Phonenumber.search(string)
# printing the result
print('mobile number found from the string : ',m.group())
Output
mobile number found from the string : 018002089898
Python String Programs »