gpt4 book ai didi

Python:尝试检查有效的电话号码

转载 作者:太空狗 更新时间:2023-10-30 01:44:54 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,它接受格式为 XXX-XXX-XXXX 的电话号码,并将条目中的任何字母转换为相应的号码。

现在我有了这个,如果开始时不正确,它将允许您重新输入正确的数字,然后它会翻译输入的原始数字。我该如何解决这个问题?

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 phone_number
elif not c.isalnum():
phone_number=input('Please enter a valid phone number: ')
return phone_number
return phone_number


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
elif char in 'DEFdef':
x4='3'
s= s + x4
elif char in 'GHIghi':
x5='4'
s= s + x5
elif char in 'JKLjkl':
x6='5'
s= s + x6
elif char in 'MNOmno':
x7='6'
s= s + x7
elif char in 'PQRSpqrs':
x8='7'
s= s + x8
elif char in 'TUVtuv':
x9='8'
s= s + x9
elif char in 'WXYZwxyz':
x10='9'
s= s + x10
print(s)

最佳答案

import re

def validNumber(phone_nuber):
pattern = re.compile("^[\dA-Z]{3}-[\dA-Z]{3}-[\dA-Z]{4}$", re.IGNORECASE)
return pattern.match(phone_nuber) is not None

关于Python:尝试检查有效的电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15258708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com