1
2
3
4
5
6
7
8
9
10 """Code for normalising and formatting phone numbers
11
12 This doesn't (yet) try to deal with international numbers.
13 The rule is that if the string contains 10 digits (with an optional
14 preceding one) then it is reduced to the 10 digits (all non-digit
15 characters removed, optional leading one removed).
16
17 If the string doesn't meet those criteria then it is passed through
18 as is.
19
20 For formatting, 10 digit strings are formatted in standard US
21 notation. All others are left as is.
22 """
23
24
25 import re
26
27 _notdigits=re.compile("[^0-9]*")
28 _tendigits=re.compile("^[0-9]{10}$")
29 _sevendigits=re.compile("^[0-9]{7}$")
30
31
33
34
35 return n
36 nums="".join(re.split(_notdigits, n))
37 if len(nums)==10:
38 return nums
39 if len(nums)==11 and nums[0]=="1":
40 return nums[1:]
41 return n
42
49
50
51 if __name__=='__main__':
52 nums=("011441223518046", "+1-123-456-7890", "(123) 456-7890", "0041-2702885504",
53 "19175551212", "9175551212", "123 456 7890", "123 456 7890 ext 17")
54
55 for n in nums:
56 print "%s\n norm: %s\n fmt: %s\n" % (n, normalise(n), format(normalise(n)))
57