简体   繁体   中英

Python. figuring out how to input a correct phone number

So I'm new to python and I'm writing a program that accepts a phone number in the format XXX-XXX-XXXX and changes any letters to their corresponding numbers. I need to check the entry and make sure it's in the correct format, and if its not, allow it to be reentered. I'm having a hard time getting it to prompt me for a new number, and even when that works sometimes, it will still translate the original, wrong phone number.

This is my code so far:

def main():
    phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
    validNumber(phone_number)
    translateNumber(phone_number)

def validNumber(phone_number):
    for i,c in enumerate(phone_number):
        if i in [3,7]:
            if c != '-':
                phone_number=input('Please enter a valid phone number: ')
            return False
        elif not c.isalnum():
            phone_number=input('Please enter a valid phone number: ')
        return False
    return True

def translateNumber(phone_number):
    s=""
    for char in phone_number:
        if char is '1':
            x1='1'
            s= s + x1
       elif char is '-':
            x2='-'
            s= s + x2
       elif char in 'ABCabc':
           x3='2'
           s= s + x3

.....etc this part isn't important

You probably want to use a while loop to force the user to input a valid number. Something like:

def main():
    phone_number = ""
    while not validNumber(phone_number):
        phone_number = input('Please enter a phone number in the format XXX-XXX-XXXX: ')
    translateNumber(phone_number)

(You may need to replace input with raw_input if you're using Python 2.7,)

Here is a full, working solution.

import re
from string import maketrans

phone_match = re.compile("^(\w{3}-\w{3}-\w{4})$")


def validPhone(number):
    match = phone_match.match(number)
    if match:
        return match.groups(0)[0]
    return None

phone_number = ''
while not validPhone(phone_number):
    phone_number = raw_input("Give me your digits!: ")

phone_in = "abcdefghijklmnopqrstuvwxyz"
phone_out = "22233344455566677778889999"
transtab = maketrans(phone_in, phone_out)

print phone_number.lower().translate(transtab)

Examples:

Give me your digits!: 949-POO-PTOO
949-766-7866

Give me your digits!: 555-HOT-KARL
555-468-5275

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM