简体   繁体   中英

How to format a list of phone numbers e.g. 202.202.2020 into (202) 202-2020 using Python?

I have a huge list of phone numbers which format is mainly eg 202.202.2020 but sometimes 2022022020 and sometimes 202 202 2020 etc.. (but they are always 10 numbers).
I would like to format all of them to using a python script.

Thanks a lot for you help.

Remove junk (. or - etc), and be left with just digits.

number = ''.join([ n for n in number if n.isdigit() ])

Then put in the format you would like.

number = '(' + number[:3] + ') ' + number[3:6] + '-' + number[6:10]

You can easily use regular expressions: http://docs.python.org/library/re.html

For example, this works for the cases you describe:

import re
regexp = re.compile('([0-9]{3}).*([0-9]{3}).*([0-9]{4})')

test = '222.222.2222'
match = regexp.match(test)
'(%s) %s-%s' % match.groups() # Gives '(222) 222-2222'

test = '222 222 2222'
match = regexp.match(test)
'(%s) %s-%s' % match.groups() # Gives '(222) 222-2222'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM