在 Python 中格式化电话号码的最佳方法是什么?
如果我只有 10 位或更多数字的字符串,如何将其格式化为电话号码?
一些琐碎的例子:
555-5555
555-555-5555
1-800-555-5555
我知道这些不是格式化它们的唯一方法,如果我自己这样做,我很可能会遗漏一些东西。是否有 python 库或格式化电话号码的标准方法?
If all I have is a string of 10 or more digits, how can I format this as a phone number?
Some trivial examples:
555-5555
555-555-5555
1-800-555-5555
I know those aren't the only ways to format them, and it's very likely I'll leave things out if I do it myself. Is there a python library or a standard way of formatting phone numbers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
对于库:电话号码(pypi,来源)
自述文件不够充分,但我发现代码有详细记录。
for library: phonenumbers (pypi, source)
The readme is insufficient, but I found the code well documented.
看起来您的示例格式为除最后一个之外的三位数字组,您可以编写一个简单的函数,使用千位分隔符并添加最后一位数字:
Seems like your examples formatted with three digits groups except last, you can write a simple function, uses thousand seperator and adds last digit:
这是改编自 utdemir 的解决方案 和 此解决方案将与Python 2.6一起使用,因为“,”格式化程序是Python中的新功能2.7.
Here's one adapted from utdemir's solution and this solution that will work with Python 2.6, as the "," formatter is new in Python 2.7.
更详细,一个依赖项,但保证大多数输入的一致输出,并且写起来很有趣:
输出:
没有幻数; ...如果您不喜欢整个简洁性:
More verbose, one dependency, but guarantees consistent output for most inputs and was fun to write:
Output:
Without magic numbers; ...if you're not into the whole brevity thing:
您可以使用函数
clean_phone()
< /a> 来自库 DataPrep。使用pip install dataprep
安装它。You can use the function
clean_phone()
from the library DataPrep. Install it withpip install dataprep
.一个简单的解决方案可能是从后面开始,在四个数字后面插入连字符,然后以三个为一组,直到到达字符串的开头。我不知道内置函数或类似的东西。
您可能会发现这很有帮助:
http://www.diveintopython3.net/regular-expressions.html#phonenumbers
如果您接受用户输入的电话号码,则正则表达式将很有用。我不会使用上面链接中遵循的确切方法。一些更简单的事情,比如去掉数字,可能更容易,而且同样好。
此外,在数字中插入逗号是一个类似的问题,该问题已在其他地方得到有效解决,并且可以适用于该问题。
A simple solution might be to start at the back and insert the hyphen after four numbers, then do groups of three until the beginning of the string is reached. I am not aware of a built in function or anything like that.
You might find this helpful:
http://www.diveintopython3.net/regular-expressions.html#phonenumbers
Regular expressions will be useful if you are accepting user input of phone numbers. I would not use the exact approach followed at the above link. Something simpler, like just stripping out digits, is probably easier and just as good.
Also, inserting commas into numbers is an analogous problem that has been solved efficiently elsewhere and could be adapted to this problem.
就我而言,我需要按国家/地区获取类似“*** *** ***”的电话模式。
所以我在我们的项目中重新使用了
phonenumbers
包In my case, I needed to get a phone pattern like "*** *** ***" by country.
So I re-used
phonenumbers
package in our project