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

时间:2015-03-16 06:17:35

标签: python string-formatting phone-number

所以,我的电话号码格式化程序实现得很差。它应该采用电话号码格式的实例值,并以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

1 个答案:

答案 0 :(得分:4)

有很多方法可以做到这一点。一个更简单的函数版本是:

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:])