【发布时间】:2018-12-16 01:52:53
【问题描述】:
如何将 10 位字符串:0123456789 格式化为电话号码格式:
(012) 345-6789
是否有特定的库可供使用,或者您可以使用正则表达式吗?
我用re.sub('[^0-9]', '', '(012) 345-6789')做了相反的事情
【问题讨论】:
标签: python regex python-3.x
如何将 10 位字符串:0123456789 格式化为电话号码格式:
(012) 345-6789
是否有特定的库可供使用,或者您可以使用正则表达式吗?
我用re.sub('[^0-9]', '', '(012) 345-6789')做了相反的事情
【问题讨论】:
标签: python regex python-3.x
您可以使用库 DataPrep 中的函数 clean_phone()。使用pip install dataprep 安装它。
>>> from dataprep.clean import clean_phone
>>> df = pd.DataFrame({'phone': ['0123456789', 1234567890]})
>>> clean_phone(df, 'phone', output_format='national')
Phone Number Cleaning Report:
2 values cleaned (100.0%)
Result contains 2 (100.0%) values in the correct format and 0 null values (0.0%)
phone phone_clean
0 0123456789 (012) 345-6789
1 1234567890 (123) 456-7890
【讨论】:
为了增强迈克的反应:
def parsephone(strphone):
'''
Pull out just the digits. Then do some simple formating.
'''
phn = ""
for n in strphone:
if n in "0123456789":
phn += n
if len(phn) == 10: # add a 1 in front
phn = "1" + phn
if len(phn) != 11:
return phn # no hope of formating
# format with dashes
phn = phn[:1] + "-" + phn[1:4] + "-" + phn[4:7] + "-" + phn[7:]
return phn
【讨论】:
将字符串切成需要分隔的部分,例如区号的前三个数字,(slicing tutorial) 然后将部分和格式连接在一起,(concatenation tutorial)。
num="0123456789"
print("("+num[:3]+")"+num[3:6]+"-"+num[6:])
【讨论】:
使用 re.sub 可让您在单个命令中处理输出字符串格式。
import re
s = '0123456789'
>>> re.sub(r'(\d{3})(\d{3})(\d{4})', r'(\1) \2-\3', s)
'(012) 345-6789'
【讨论】:
你也可以使用像phonenumbers这样的库?
安装它:
pip install --user phonenumbers
代码示例:
import phonenumbers
phonenumbers.format_number(phonenumbers.parse("0123456789", 'US'),
phonenumbers.PhoneNumberFormat.NATIONAL)
输出:
'(012) 345-6789'
【讨论】:
import re
print('(%s) %s-%s' % tuple(re.findall(r'\d{4}$|\d{3}', '0123456789')))
这个输出:
(012) 345-6789
【讨论】: