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

后端 未结 4 1262
慢半拍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:34

    A simple solution might be to start at the back and insert the hyphen after four numbers, then do groups of three until the beginning of the string is reached. I am not aware of a built in function or anything like that.

    You might find this helpful: http://www.diveintopython3.net/regular-expressions.html#phonenumbers

    Regular expressions will be useful if you are accepting user input of phone numbers. I would not use the exact approach followed at the above link. Something simpler, like just stripping out digits, is probably easier and just as good.

    Also, inserting commas into numbers is an analogous problem that has been solved efficiently elsewhere and could be adapted to this problem.

提交回复
热议问题