What's the best way to format a phone number in Python?

后端 未结 4 1258
慢半拍i
慢半拍i 2020-12-01 20:32

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
         


        
4条回答
  •  天命终不由人
    2020-12-01 21:33

    Seems like your examples formatted with three digits groups except last, you can write a simple function, uses thousand seperator and adds last digit:

    >>> def phone_format(n):                                                                                                                                  
    ...     return format(int(n[:-1]), ",").replace(",", "-") + n[-1]                                                                                                           
    ... 
    >>> phone_format("5555555")
    '555-5555'
    >>> phone_format("5555555")
    '555-5555'
    >>> phone_format("5555555555")
    '555-555-5555'
    >>> phone_format("18005555555")
    '1-800-555-5555'
    

提交回复
热议问题