Format an un-decorated phone number in django?

后端 未结 5 764
我在风中等你
我在风中等你 2021-01-02 13:01

I\'ve got a DB chock full o\' phone numbers as strings, they\'re all formatted like 1112223333, I\'d like to display it as 111-222-3333 in my django template

I know

5条回答
  •  囚心锁ツ
    2021-01-02 13:15

    def formatPhone(phone):
        formatted = ''
        i = 0
    
        # clean phone. skip not digits
        phone = ''.join(x for x in phone if x.isdigit())
    
        # set pattern
        if len(phone) > 10:
            pattern = 'X (XXX) XXX-XX-XX'
        else:
            pattern = 'XXX-XXX-XX-XX'
    
        # reverse
        phone = phone[::-1]
        pattern = pattern[::-1]
    
        # scan pattern
        for p in pattern:
            if i >= len(phone):
                break
    
            # skip non X
            if p != 'X':
                formatted += p
                continue        
    
            # add phone digit
            formatted += phone[i]
            i += 1
    
        # reverse again    
        formatted = formatted[::-1]
    
        return formatted
    

    print formatPhone('+7-111-222-33-44')

    7 (111) 222-33-44

    print formatPhone('222-33-44')

    222-33-44

    print formatPhone('23344')

    2-33-44

提交回复
热议问题