Search code examples
pythonzapier

Extract phone number and convert to whatsapp format


Im new to python, and I need to use it inside my Zapier automation. In my automation, I want to convert phone numbers from various format to specific format (whatsapp url purpose). How can I extract and convert below inputs to specific output using python?

input:
+62 812-3456-7890
62081234567890
6281234567890
+6281234567890
081234567890
(62)81234567890
(62)081234567890
(+62)81234567890
(+62)081234567890

output:
6281234567890

Additional information: "62" is the country code for Indonesia typically 8-12 digits including a "0" prefixing the "8nn"

Thank you in advance


Solution

  • It is not the most optimal solution, but I wanted to keep it very simple, because you are a beginner in python.

    def decode(number: str):
        chars = ['+', '(', ')', '-', ' ']
        for c in chars:
            number = number.replace(c, '')
    
        return number
            
    print(decode('+62 812-3456-7890'))
    print(decode('(62)81234567890'))
    

    chars is a list of characters that you want to remove from a number.

    EDIT I tried to test every number you gave in the question and I found out that code above doesn't work as you wanted. Here's my new solution and it passes all tests:

    def decode(number: str):
        chars = ['+', '(', ')', '-', ' ']
        for c in chars:
            number = number.replace(c, '')
    
        if number.startswith('0'):
            number = number[1:]
        if not number.startswith('62'):
            number = f'62{number}'
        if number[2] == '0':
            number = number.replace('0', '', 1)
    
        return number
    
    tests = """+62 812-3456-7890
    62081234567890
    6281234567890
    +6281234567890
    081234567890
    (62)81234567890
    (62)081234567890
    (+62)81234567890
    (+62)081234567890"""
            
    for num in tests.split('\n'):
        print(decode(num))
    

    I added some if statments to handle all tests exeptions and also added test for each test case you gave.

    The output of tests:

    6281234567890
    6281234567890
    6281234567890
    6281234567890
    6281234567890
    6281234567890
    6281234567890
    6281234567890
    6281234567890