在Python中格式化电话号码的最佳方法是什么?

48 投票
7 回答
82207 浏览
提问于 2025-04-16 23:35

如果我手里只有一串10个或更多数字,我该怎么把它格式化成电话号码呢?

这里有一些简单的例子:

555-5555
555-555-5555
1-800-555-5555

我知道这并不是格式化电话号码的唯一方法,如果我自己来做,很可能会遗漏一些东西。有没有什么Python库或者标准的方法可以用来格式化电话号码呢?

7 个回答

6

这里有一个改编自 utdemir的解决方案这个解决方案 的例子,它可以在Python 2.6中使用,因为在Python 2.7中才引入了“,”这种格式化方式。

def phone_format(phone_number):
    clean_phone_number = re.sub('[^0-9]+', '', phone_number)
    formatted_phone_number = re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1-", "%d" % int(clean_phone_number[:-1])) + clean_phone_number[-1]
    return formatted_phone_number
36

看起来你的例子是用三位一组的格式,除了最后一组。你可以写一个简单的函数,使用千位分隔符,并在最后加上一个数字:

>>> def phone_format(n):                                                                                                                                  
...     return format(int(n[:-1]), ",").replace(",", "-") + n[-1]                                                                                                           
... 
>>> phone_format("5555555")
'555-5555'
>>> phone_format("5555555")
'555-5555'
>>> phone_format("5555555555")
'555-555-5555'
>>> phone_format("18005555555")
'1-800-555-5555'
62

这个库叫做 phonenumbers(pypi, 源代码

这是一个用 Python 写的库,主要用于解析、格式化、存储和验证国际电话号码,灵感来自于谷歌的一个常用库。

虽然说明文档不太够用,但我发现代码的注释写得很清楚。

撰写回答