[英]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). 我有大量的电话号码,其格式主要是例如202.202.2020,但有时是2022022020,有时是202202 2020等(但它们始终是10个数字)。
I would like to format all of them to (202) 202-2020 using a python script.
我想使用python脚本将所有格式设置为(202)202-2020 。
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 您可以轻松使用正则表达式: 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.