用Python判断手机号码的运营商

本文介绍了如何使用Python来判断输入的手机号码属于移动、联通还是电信运营商。在短信验证前,程序会根据号码长度和号段进行真实性校验,简化处理不考虑非数字输入。通过分析手机号码的字符串特性,并针对3位和4位号段编写匹配代码,实现了号码段的判断。

现在的APP一般在注册应用的时候,都会让用户输入手机号码,在短信验证之前首先会验证号码的真实性,如果是不存在的号码,就不会发送验证码。检验规则如下:

  1. 长度不小于11位
  2. 是移动,联通,电信号段中的任意一个
  3. 不考虑输入非数字的情况(简化程序)
  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]

程序效果如下:

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()

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值