python将字母转换为电话号码
我是python编程的初学者。这是我第一个学期学习编程。我有点小麻烦。我们正在使用字符串,因此我猜我必须将所有内容转换为字符串。因此,此问题的目标是将电话号码转换为以下文字: 1-800-flowers至1-800-3569377 我不允许使用列表或字典,只能使用变量,并且必须包含WHILE循环。这就是我到目前为止所做的:python将字母转换为电话号码,python,while-loop,Python,While Loop,我是python编程的初学者。这是我第一个学期学习编程。我有点小麻烦。我们正在使用字符串,因此我猜我必须将所有内容转换为字符串。因此,此问题的目标是将电话号码转换为以下文字: 1-800-flowers至1-800-3569377 我不允许使用列表或字典,只能使用变量,并且必须包含WHILE循环。这就是我到目前为止所做的: print('format: X-XXX-XXXXXXX') user_input = str(input("give me a phone number: ")) ke
print('format: X-XXX-XXXXXXX')
user_input = str(input("give me a phone number: "))
key_alph='abcdefghijklmnopqrstuvwxyz'
key_num= '22233344455566677778889999'
total=''
while user_input[6:12].isalpha():
if user_input[6:12] in key_alph:
print(user_input[:6] ,key_num)
任何帮助都将不胜感激。
如果可能的话,答案可能不会透露,但如果oyuu不得不解释,那就好了。我不知道是否需要使用index函数或.append方法。。。。
先谢谢你
danny m我很想说,如果用户输入在变量key\u alph中,那么无论key\u alph对应的字母是什么,都要打印出key\u num。不要试图一次处理所有字符,而是需要逐个字符扫描。你的while循环可以类似于
while i
。你的while/if/print整件事毫无意义,[6:12]指的是从位置6到位置12的子字符串,并且没有改变。我的答案有什么问题吗?输入您提供的测试数据,您将清楚地看到正确的答案。这取决于用户如何处理该情况,但我在else条件下处理该情况,方法是保持原样。问题清楚地表明,解决方案必须包括使用while循环。感谢@anmol\u uppal提供答案。你有个人电子邮件地址吗?是的,我想是在简历中提到的@DanielMedina@anmol uppal-什么函数是“alpha=用户输入[-counter]”,其中[-counter]是。这是一个索引函数吗?我知道alpha将是一个新的变量。你能不能更详细地解释一下总+=key_num[key_alph.index(alpha)]是什么。。。在键数之后。。。如果这是一个索引函数,我以前试过,但它不允许我这样做,因为它总是说INT是不可数的。
user_input = (input("give me a phone number: "))
key_alph='abcdefghijklmnopqrstuvwxyz'
key_num= '22233344455566677778889999'
counter = len(user_input[:6])
total=user_input[:6] #Stores the part of string which is not going to be changed ("1-800-")
while (counter>0):
alpha = user_input[-counter]
if alpha.isalpha(): #checks if each character in the input is a valid alphabet and not a number.
total+=key_num[key_alph.index(alpha)] #Appending the new characters after the "1-800-"
else:
total+=alpha #This will preserve if any numeric character is encountered and keeps it same as in the input
counter -= 1
print total