- 编写代码的一般步骤
- 明确需求
- 理解需求
- 对问题进行概括
- 编写代码
- 测试调试代码
- 需求
- 输入一串字符串 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
- 把电话号码(415-555-1011,415-555-9999)提取出来
- 判断电话号码究竟是什么格式,考虑一下它的规律:只有数字和‘-’两种字符,而且第三位和第七位一定是‘-’,这个时候考虑用数据驱动方式来写;
-
代码如下
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 传进去就可以知道结果 - 测试结果
-
分类
初识Python,第一个小程序,判断电话号码
阅读(794) 评论(0)