Program to find reformatted phone number in Python


Suppose we have a phone number as string. The phone number number consists of digits, spaces and/or dashes '-'. We want to reformat the phone number in a certain manner. There are few rules −

  • Remove all spaces and dashes at beginning

  • Group the digits from left side to right side into blocks of length 3 until there are 4 or less digits are left.

  • The final digits are then grouped like −

    • For 2 digits: A single block of length 2.

    • For 3 digits: A single block of length 3.

    • For 4 digits: Two more blocks of length 2 each.

These blocks are then clubbed by dashes. We have to find the reformatted phone number.

So, if the input is like s = "9-6-84102-4 7-8", then the output will be “968-410-24-78”

To solve this, we will follow these steps −

  • digits := a blank string

  • blk := a blank string

  • for each character i in s, do

    • if i is numeric, then

      • blk := blk concatenate i

    • if size of blk is same as 3, then

      • digits := digits concatenate blk concatenate dash("-")

      • blk := a blank string

  • if size of blk is same as 0, then

    • return substring of digits from index 0 to size of digits-1]

  • otherwise when size of blk is same as 1, then

    • return substring of digits from index 0 to size of digits-2] concatenate dash("-") concatenate second last character of digits concatenate blk

  • otherwise when size of blk is same as 2, then

    • return digits concatenate blk

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

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]
   elif len(blk) == 1:
      return digits[:-2]+"-"+digits[-2]+blk
   elif len(blk) == 2:
      return digits+blk

s = "9-6-84102-4 7-8"
print(solve(s))

Input

"9-6-84102-4 7-8"

Output

968-410-24-78

Updated on: 18-May-2021

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements