Python Forum
Format phonenumbers - regular expressions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Format phonenumbers - regular expressions
#1
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
Reply
#2
(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']
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Great! Thanks! :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Recursive regular expressions in Python risu252 2 1,262 Jul-25-2023, 12:59 PM
Last Post: risu252
Sad Regular Expressions - so close yet so far bigpapa 5 970 May-03-2023, 08:18 AM
Last Post: bowlofred
  Having trouble with regular expressions mikla 3 2,598 Mar-16-2021, 03:44 PM
Last Post: bowlofred
  Statements and Expressions Julie 1 1,642 Feb-26-2021, 05:19 PM
Last Post: nilamo
  Convert date integers (ex. 43831) to regular format Galven 2 2,643 Nov-15-2020, 11:38 PM
Last Post: bowlofred
  Regular Expressions pprod 4 3,093 Nov-13-2020, 07:45 AM
Last Post: pprod
  regular expressions in openpyxl. format picnic 0 2,488 Mar-28-2020, 09:47 PM
Last Post: picnic
  Unexpected (?) result with regular expressions guraknugen 2 2,228 Jan-18-2020, 02:33 PM
Last Post: guraknugen
  Strange output with regular expressions newbieAuggie2019 1 1,941 Nov-04-2019, 07:06 PM
Last Post: newbieAuggie2019
  Regular Expressions amitalable 4 2,780 Mar-14-2019, 04:31 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020