Python Forum
Format phonenumbers - regular expressions - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Format phonenumbers - regular expressions (/thread-26727.html)



Format phonenumbers - regular expressions - Viking - May-11-2020

Hi,

I am trying to format a list of phonenumbers.

I want to move through the list and do the same operation on each number, I have figured out how to do it one number at a time.

Would an option be to add a for loop?

import re

# List with phonenumbers
number = ['072 5674 323', "072 540 6789", "0047735 648975"]

# Remove spaces
num = re.sub(r'\D', "", number[0])

# Read backwards 
num_1 = num[-9:]

#Print country code + formated number 
print(F"0047{num_1}")

#Output
0047735674323



RE: Format phonenumbers - regular expressions - buran - May-11-2020

(May-11-2020, 06:44 PM)Viking Wrote: Would an option be to add a for loop?
yes, or use list comprehension. And no need of regex too
numbers = ['072 5674 323', "072 540 6789", "0047735 648975"]
formated_numbers = [f"0047{number.replace(' ', '')[-9:]}" for number in numbers]
print(formated_numbers
Output:
['0047725674323', '0047725406789', '0047735648975']



RE: Format phonenumbers - regular expressions - Viking - May-11-2020

Great! Thanks! :)