现在的APP一般在注册应用的时候,都会让用户输入手机号码,在短信验证之前首先会验证号码的真实性,如果是不存在的号码,就不会发送验证码。检验规则如下:
- 长度不小于11位
- 是移动,联通,电信号段中的任意一个
- 不考虑输入非数字的情况(简化程序)
- 移动号段,联通号段,电信号段如下:
CN_mobile = \
[134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,
187,188,147,178,1705]
CN_union = [130,131,132,155,156,185,186,145,176,1709]
CN_telecom = [133,153,180,181,189,177,1700]
程序效果如下:
Enter your number :123
Invalid length, your number should be in 11 digits
Enter your number :12312345678
No such an operator
Enter your number :18812345678
Operator : China Mobile
We're sending verification code via text to your phone: 18812345678
分析:
输入的手机号码默认是string字符串,而题目中给出的是list列表,所以需要有一步转换,显然是转换成字符串操作比较容易。
发现号码段中同时出现了3位和4位的数字,所以要用两个字符串去匹配,匹配的代码为
key in statement
代码:
# 校验手机号码的真实性
def judge_operator(phone_num):
id3 = phone_num[0:3]
id4 = phone_num[0:4]
CN_mobile = \
[134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,
187,188,147,178,1705]
CN_union = [130,131,132,155,156,185,186,145,176,1709]
CN_telecom = [133,153,180,181,189,177,1700]
if ((id3 in str(CN_mobile)) or (id4 in str(CN_mobile))):
return "China Mobile"
elif ((id3 in str(CN_union)) or (id4 in str(CN_union))):
return "China Union"
elif ((id3 in str(CN_telecom)) or (id4 in str(CN_telecom))):
return "China Telecom"
else:
return 0
def verify_phone_number():
phone_number = input("Enter your number :")
invalid = len(phone_number)<11
# print(invalid)
if (invalid):
# print(invalid)
print("Invalid length, your number should be in 11 digits")
verify_phone_number() # 函数递归调用
else:
operator = judge_operator(phone_number) # 返回的是字符串
if (operator):
print("Operator : {}".format(operator))
print("We're sending verification code via text to your phone: {}".format(phone_number))
else:
print("No such an operator")
verify_phone_number() # 函数递归调用
verify_phone_number()
本文介绍了如何使用Python来判断输入的手机号码属于移动、联通还是电信运营商。在短信验证前,程序会根据号码长度和号段进行真实性校验,简化处理不考虑非数字输入。通过分析手机号码的字符串特性,并针对3位和4位号段编写匹配代码,实现了号码段的判断。
1万+

被折叠的 条评论
为什么被折叠?



