用于验证正确输入的电话号码的Python程序

时间:2015-04-04 23:39:51

标签: python

这是我到目前为止所做的,虽然它没有正常工作。任何有关变化的建议都表示赞赏。

def get_telephone_number(areacode, prefix, number):
    set1 = areacode[0:3]
    set2 = prefix[0:3]
    set3 = number[-3:]

    telephone_number=set1 + '-' + set2 + '-' + set3

    return get_telephone_number


def valid_telephone_number(telephone_number):
    correct_length = False
    proper_hyphens = False
    has_digits = False

    if len(telephone_number) == 12:
        correct_length = True

    for ch in telephone_number:
        if ch [3, 7] == '-':
            proper_hypens = True
        if ch.isdigit():
            has_digits = True

    if correct_length and proper_hypens and has_digits:
        is_valid = True
    else:
        is_valid = False

    return is_valid
###########

import telephone_number

def main():
    phone_number = input('Enter your telephone number: ')

    while not phone_number.valid_telephone_number(telephone_number):  
        print('That number is invalid.')
        phone_number = input('Enter your telephone number: ')

    print('That is a valid entry.')

main()

1 个答案:

答案 0 :(得分:2)

不确定您想要的确切格式,但使用正则表达式可能会更容易:

import  re
s ="043-4443-344"
n = re.match("^\d+-\d+-\d+$",s)
if n:
    print(n.group())

"^\d+-\d+-\d+$"将匹配以一个或多个数字后跟连字符开头的字符串,一个或多个数字后跟连字符并以一个或多个数字结尾。如果您想允许使用特定数量的数字,例如^\d{3,5},则区号将介于3-5位数之间。

你的第一次检查可能应该是if len(phone_number) != 12,因为如果没有,那就没有任何意义了。

如果您想在没有正则表达式的情况下执行此操作,则可以执行以下操作:

def valid_telephone_number(inp):
    # make sure len is 12 and all char at index 3 and 7  are -
    if not all(inp[x] == "-" for x in [3,7])and len(inp) == 12:
        return False
    # will be True if all that is left are digits after removing the - else False
    return inp.replace("-", "", 3).isdigit()



def main():
    while True:
        phone_number = input('Enter your telephone number: ')
        check = valid_telephone_number(phone_number)
        # will be True for a valid num so return the formatted input
        if check:
            return check
        # or else print message telling use the input was invalid and ask again
        print('{} is a not valid entry, please try again.'.format(phone_number))