Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find reformatted phone number in Python
Phone number formatting is a common task in data processing. Given a phone number string containing digits, spaces, and dashes, we need to reformat it according to specific grouping rules.
Problem Requirements
The reformatting follows these rules:
Remove all spaces and dashes first
Group digits from left to right into blocks of 3 until 4 or fewer digits remain
-
Handle the final digits based on count:
2 digits: Single block of length 2
3 digits: Single block of length 3
4 digits: Two blocks of length 2 each
Join all blocks with dashes
Example
For input "9-6-84102-4 7-8", the output should be "968-410-24-78".
Solution Implementation
def solve(s):
digits = ""
blk = ""
for i in s:
if i.isnumeric():
blk += i
if len(blk) == 3:
digits += blk + "-"
blk = ""
if len(blk) == 0:
return digits[:-1] # Remove trailing dash
elif len(blk) == 1:
return digits[:-2] + "-" + digits[-2] + blk
elif len(blk) == 2:
return digits + blk
elif len(blk) == 4:
return digits + blk[:2] + "-" + blk[2:]
else: # len(blk) == 3
return digits + blk
# Test the function
s = "9-6-84102-4 7-8"
print(solve(s))
968-410-24-78
How It Works
The algorithm processes the input character by character:
Extract digits: Only numeric characters are added to the current block
Form groups: When a block reaches 3 digits, it's added to the result with a dash
Handle remainder: After processing all characters, format the remaining digits according to the rules
Alternative Approach
Here's a cleaner implementation that first extracts all digits, then formats them:
def reformat_phone(s):
# Extract only digits
digits = ''.join(char for char in s if char.isdigit())
result = []
i = 0
# Group into blocks of 3 while more than 4 digits remain
while len(digits) - i > 4:
result.append(digits[i:i+3])
i += 3
# Handle the remaining digits
remaining = len(digits) - i
if remaining == 4:
result.append(digits[i:i+2])
result.append(digits[i+2:i+4])
else:
result.append(digits[i:])
return '-'.join(result)
# Test cases
test_cases = ["9-6-84102-4 7-8", "123-456-789", "12 34 56 78 90"]
for phone in test_cases:
print(f"Input: '{phone}' ? Output: '{reformat_phone(phone)}'")
Input: '9-6-84102-4 7-8' ? Output: '968-410-24-78' Input: '123-456-789' ? Output: '123-456-789' Input: '12 34 56 78 90' ? Output: '123-456-78-90'
Conclusion
Phone number reformatting involves extracting digits and grouping them according to specific rules. The key is handling the final group correctly based on the remaining digit count.
