如何在python中格式化电话号码

2024-10-01 17:35:09 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我有一个非常糟糕的电话号码格式化程序的实现。它应该采用电话号码格式的实例值,并以xxx.xxx.xxxx(目前只能是美国电话号码)

代码可以在这个要点上找到:https://gist.github.com/trtmn/a5a51c3da55ae0b32ac8

    phone = models.CharField(max_length=20, blank=True)
def formatphone(self): #Dear Future Self - I'm so very sorry.
    formattedphone = ""
    for x in self.phone:
        if x == "1":
            formattedphone = formattedphone + x
        if x == "2":
            formattedphone = formattedphone + x
        if x == "3":
            formattedphone = formattedphone + x
        if x == "4":
            formattedphone = formattedphone + x
        if x == "5":
            formattedphone = formattedphone + x
        if x == "6":
            formattedphone = formattedphone + x
        if x == "7":
            formattedphone = formattedphone + x
        if x == "8":
            formattedphone = formattedphone + x
        if x == "9":
            formattedphone = formattedphone + x
        if x == "0":
            formattedphone = formattedphone + x
    if len(formattedphone) == 11:
        formattedphone = formattedphone[1] + formattedphone[2] + formattedphone[3] + "." + formattedphone[4] + formattedphone[5] + formattedphone[6] + "." + formattedphone[7] + formattedphone[8] + formattedphone[9] + formattedphone[10]
    if len(formattedphone) == 10:
        formattedphone = formattedphone[0] + formattedphone[1] + formattedphone[2] + "." + formattedphone[3] + formattedphone[4] + formattedphone[5] + "." + formattedphone[6] + formattedphone[7] + formattedphone[8] + formattedphone[9]
    return formattedphone

Tags: 实例代码httpsself程序lenif格式
1条回答
网友
1楼 · 发布于 2024-10-01 17:35:09

有很多方法可以做到。更简单的功能是:

def format_phone(self):
    # strip non-numeric characters
    phone = re.sub(r'\D', '', self.phone)
    # remove leading 1 (area codes never start with 1)
    phone = phone.lstrip('1')
    return '{}.{}.{}'.format(phone[0:3], phone[3:6], phone[6:])

相关问题 更多 >

    热门问题