0

I would like to transform a phone number of this form +33.300000000 in 03.00.00.00.00

+33 is the indicatif it could be 2 or 3 digits length.

Digits after the . are the phone number. It could be 9 or 10 digits length.

I try like this :

p = re.compile( "\+[0-9]+\.([0-9]+)", re.VERBOSE)
number = "+33.300000000"
p.sub("0\1", number)

But this doesn't work.

However, the search seams to work :

>>> p.search(number).groups()
('300000000',)

And after how to modify 0300000000 in 03.00.00.00.00 in Python ?

Thank you for your help,

Natim

2
  • For nine digits you add a leading 0, what happens for 10 digits? Commented Oct 11, 2009 at 23:58
  • Yes, you replace the telephone code with a 0 Commented Oct 12, 2009 at 0:04

2 Answers 2

3

The simplest approach is a mix of RE and pure string manipulation, e.g.:

import re

def doitall(number):
  # get 9 or 10 digits, or None:
  mo = re.search(r'\d{9,10}', number)
  if mo is None: return None
  # add a leading 0 if they were just 9
  digits = ('0' + mo.group())[-10:]
  # now put a dot after each 2 digits
  # and discard the resulting trailing dot
  return re.sub(r'(\d\d)', r'\1.', digits)[:-1]

number = "+33.300000000"
print doitall(number)

emits 03.00.00.00.00, as required.

Yes, you can do it all in a RE, but it's not worth the headache -- the mix works fine;-).

Sign up to request clarification or add additional context in comments.

2 Comments

you can also use digits = mo.group().zfill(10)
and return ".".join(re.findall(r'(\d\d)',digits))
0

In the terminal it works like that :

p = re.compile( "\+[0-9]+\.([0-9]+)", re.VERBOSE)
number = "+33.300000000"
p.sub("0\\1", number)

And in the python script it works like that :

p = re.compile( "\+[0-9]+\.([0-9]+)", re.VERBOSE)
number = "+33.300000000"
p.sub("0\1", number)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.