How to string replace in a list of phone numbers in python?

I have these phone numbers in a list:

+61 2 3456 2718
03 2756 2876
4567 8937 
+61 5 6573 8593
05 8583 7932

I want to remove the first digit, if 0, and put +61 in every number. How can I do this?

import re 
for i in phone:
    print(re.sub(r"(\+?\d{3})(\d{4})(\d+)", r"\1 \2 \3", i))
    re.sub('^\d+', '', i)

4 answers

  • answered 2019-05-15 03:44 Grismar

    If all the phone numbers start with either a 0 or some international code like +61 (or another international code) and you don't need any other checks, your code could be as simple (and legible) as:

    fixed_phone_numbers = [f'+61{n[1:]}' if n[0] == '0' else n for n in phone_numbers]
    

    If, for some reason, you'd want to do this in Python 2:

    fixed_phone_numbers = ['+61' + n[1:] if n[0] == '0' else n for n in phone_numbers]
    

  • answered 2019-05-15 03:44 King Stone

    phone = ["+61 2 3456 2718",
    "03 2756 2876",
    "4567 8937 ",
    "+61 5 6573 8593",
    "05 8583 7932"]
    import re 
    for i in phone:
        if(not i.startswith('+61')):
          if(re.match(r'^0', i)):
            i = re.sub('^0', '+61', i)
          else:
            i = '+61 ' + i
        print(i)
    
    +61 2 3456 2718
    +613 2756 2876
    +61 4567 8937
    +61 5 6573 8593
    +615 8583 7932
    

  • answered 2019-05-15 03:48 mahbubcseju

    You can check the first character .If it is '0' then replaced the string by "+61"+ "substring_of_phone_number_from_position_1" (i[1:]).

    import re 
    for i in phone:
        if i[0]=='0':
            i='+61'+i[1:]
        elif i[0]!='+':
            i='+61'+i
    

  • answered 2019-05-15 04:09 Albin Paul

    Hope it helps :-). I used just regex for this

    In [1]: strings = """+61 2 3456 2718
       ...: 03 2756 2876
       ...: 4567 8937 
       ...: +61 5 6573 8593
       ...: 05 8583 7932"""
    In [3]: import re
    
    In [12]: for phoneno in strings.split('\n'):
        ...:     print(re.sub(r'^(0|\+61|)',r'+61',phoneno))
        ...:     
        ...:     
    
    +61 2 3456 2718
    +613 2756 2876
    +614567 8937 
    +61 5 6573 8593
    +615 8583 7932