1 #coding:utf-8
2 #__author__ = 'Diva'
3
4 PHONE_NUMBER_SIZE = 12 # 定義全局變量,電話號碼的長度
5
6 def is_digital(ch): # 判斷是否是數字
7 if ord(ch) >= ord('0') and ord(ch) <= ord('9'):
8 return True
9 return False
10
11 def is_special(ch): # 判斷是否是‘-’
12 if ord(ch) == ord('-'):
13 return True
14 return False
15
16 def is_phone_number_check(chars): # 判斷格式
17 if len(chars) != PHONE_NUMBER_SIZE:
18 return False
19
20 for i in range(PHONE_NUMBER_SIZE):
21 if not is_digital(chars[i]) and not is_special(chars[i]): # 不是數字或者‘-’的退出
22 return False
23 if (i == 3 or i == 7) and not is_special(chars[i]): # 第三位和第七位不是‘-’的退出
24 return False
25 if (i != 3 and i != 7) and not is_digital(chars[i]): # 排除第三和第七,如果不是數字退出
26 return False
27 return True
28
29 def split_phone_number(message): # 篩選出號碼,進行判斷
30 for n in range(len(message)):
31 chars = message[n:n + PHONE_NUMBER_SIZE]
32 if is_phone_number_check(chars):
33 print('找到電話號碼為:' + chars)
34 print('Done.')
35
36 if __name__ == '__main__':
37 message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
38 split_phone_number(message)
# 最好是用戶什么都不需要做,只要把參數傳進去就好了;函數本來就有隱藏實現的作用:main 函數里只要把 message 傳進去就可以知道結果