简体   繁体   English

如何使用Python将电话号码列表(例如202.202.2020)格式化为(202)202-2020?

[英]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.

相关问题 如何使用 Python 或 R 对大型文本语料库(例如职位列表)进行聚类? - How to cluster a large text corpus (e.g. list of job titles) using Python or R? 如何在 python 中将军用时间格式(例如 1305)转换为 hh:mm(例如 13:05)? - How to convert military time format (e.g. 1305) to hh:mm (e.g. 13:05) in python? 如何在 python3 中使用非常小的浮点数(例如 8.5e-350) - How to work with very small float numbers in python3 (e.g. 8.5e-350) 我们如何 label 矩阵 plot 与预定义的标签列表(例如素数列表)? - How do we label a matrix plot with a predefined list of labels (e.g. a list of prime numbers)? 如何检查Iterable中是否有任何奇数/偶数(例如列表/元组)? - How to check if there's any odd/even numbers in an Iterable (e.g. list/tuple)? Python:如何使用列表在列表之间进行复制,例如 list1[index1] = list2[index2] - Python: how to copy between lists using lists, e.g. list1[index1] = list2[index2] 如何在 Flask 中返回 202 Accepted? - How to return 202 Accepted in Flask? 你如何获得 python 包的 pydoc 可访问路径列表,例如 numpy 或 tensorflow? - How do you get a list of pydoc accessible paths for a python package, e.g. numpy or tensorflow? 使用NLTK查找事物列表(例如河流列表) - Find a list of things (e.g. a list of rivers) using NLTK 如何使用计算方法(例如使用Python)找到以下所需概率? - How to find the following desired probability using computational method (e.g. using Python)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM