Python Practice › String Programs › Program 106
Extract 10-digit mobile numbers
Write a Python program to get all 10-digit mobile numbers from a string.
Input
a paragraph containing short numbers and four 10-digit numbers
Output
['8988858683', '2312245566', '4532892234', '9999234355']
Approach
- Match exactly 10 digits with word boundaries.
Solution
import re text = """We have 2233 some employee8988858683whos 3455 mobile numbers are randomly distributed2312245566we want 453452 to get4532892234all the mobile numbers9999234355from this given string."""print(re.findall(r"\b\d{10}\b", text))Output
['8988858683', '2312245566', '4532892234', '9999234355']
Line by line
Line 11
\b stops a match inside a longer number, and {10} requires exactly ten digits.
Learn the concept
New to this topic? Read the lesson, then come back.