×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python program to extract phone number from string using sub() method

Here, we will see a Python program to extract phone number from string using sub() method.
Submitted by Shivang Yadav, on March 10, 2021

The regular expression in Python is a search pattern formed by a sequence of characters.

The sub() method is used to replace all occurrences of a pattern in the string with a substring/character. There is an upper limit to replacing characters.

The method returns a string that contains characters after replacing the character. The method is included in the re library.

Syntax:

regular.sub(regularExp, replaceChar, string, UL)

Let's take an example to understand the problem,

Input:
string = "Your mobile number is : 9988-214-631"

Output:
9988214631

Program to illustrate the working of our solution

import re

myString = "Your mobile number is : 9988-214-631"
print("String\t: ",myString)

convNum = re.sub(r'\D' , "" , myString)
print("Phone\t: " , convNum)

Output:

String  :  Your mobile number is : 9988-214-631
Phone   :  9988214631

Python Regular Expression Programs »



Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.