views:

69

answers:

2

Hello,

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

A: 

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)
Natim
+3  A: 

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;-).

Alex Martelli
you can also use `digits = mo.group().zfill(10)`
gnibbler
Ok, it is exactly that. Thank you.
Natim
and `return ".".join(re.findall(r'(\d\d)',digits))`
gnibbler