python converting strings into three blocks and if not two blocks

  python-3.x, re, regex

I want to write a function that converts the given string T and group them into three blocks.
However, I want to split the last block into two if it can’t be broken down to three numbers.
For example, this is my code

import re

def num_format(T):
    clean_number = re.sub('[^0-9]+', '', T)
    formatted_number = re.sub(r"(d{3})(?=(d{3})+(?!d{3}))", r"-", clean_number) 
    return formatted_number


num_format("05553--70002654")

this returns : ‘055-537-000-2654’ as a result.
However, I want it to be ‘055-537-000-26-54’.
I used the regular expression, but have no idea how to split the last remaining numbers into two blocks!

I would really appreciate helping me to figure this problem out!!
Thanks in advance.

Source: Python-3x Questions

LEAVE A COMMENT