如何在 python 中格式化 phone 数字

How to format a phone number in python

所以,我的 phone 数字格式化程序的实现非常糟糕。它应该采用 phone 数字格式的实例值,并采用 xxx.xxx.xxxx 格式的 return (目前它应该只是美国 phone 数字)

代码可以在这个要点上找到: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

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

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