Python将电话信转换为数字问题

时间:2018-11-11 18:01:56

标签: python python-3.x

我知道在此网站上曾有人问过这个问题,但是我无法理解给出的答案(我仍然很新),因此我将尝试再次询问。我的任务是编写使用10位数字的电话号码(XXX-XXX-XXXX)并将任何字母(即800-FLO-WERS)转换为数字的代码。我为此动了脑筋,真的可以使用一些帮助/解释。在我正在上的课中(使用出色的“ Tony Gaddis撰写的第4版Python入门”),我不能使用我们没有涵盖的概念(如字典),但可以使用列表/元组。 ve提出如下:

def main():
    try:
        user_number = str(input('Enter a phone number (XXX-XXX-XXXX): ')).upper()
        converted_number = check_number(user_number)
        print('The phone number is:',converted_number
    except Exception as err:
        print(err)
def check_number(user_number):
    try:
        for char in user_number:
            if char.isalpha():
                result = convert_to_num(char)
                return result
            else:
                return char
        return converted_number
    except Exception as err:
        print(err)
def convert_to_num(char):
    if char in ['A','B','C']:
        char = 2
    elif char in ['D','E','F']:
        char = 3
    elif char in ['G','H','I']:
        char = 4
    elif char in ['J','K','L']:
        char = 5
    elif char in ['M','N','O']:
        char = 6
    elif char in ['P','Q','R','S']:
        char = 7
    elif char in ['T','U','V']:
        char = 8
    elif char in ['W','X','Y','Z']:
        char = 9
    return char
main()

很明显,我不确定如何存储转换后的字母到数字(考虑通过索引来实现,但是也不能完全做到这一点)。我并不想找任何人为我做我的工作,但是详细说明我做错的事情会很可爱。

2 个答案:

答案 0 :(得分:0)

return的目的是返回到调用它的函数。因为for char in user_number: if char.isalpha(): result = convert_to_num(char) return result else: return char return converted_number 在循环内。它将在第一次迭代中退出该函数。

join()

仅使用列表来存储转换后的值,然后在循环后使用def main(): try: user_number = str(input('Enter a phone number (XXX-XXX-XXXX): ')).upper() converted_number = check_number(user_number) print('The phone number is:',converted_number) except Exception as err: print(err) def check_number(user_number): try: r = [] for char in user_number: if char.isalpha(): result = convert_to_num(char) r.append(str(result)) else: r.append(char) return "".join(r) except Exception as err: print(err) def convert_to_num(char): if char in ['A','B','C']: char = 2 elif char in ['D','E','F']: char = 3 elif char in ['G','H','I']: char = 4 elif char in ['J','K','L']: char = 5 elif char in ['M','N','O']: char = 6 elif char in ['P','Q','R','S']: char = 7 elif char in ['T','U','V']: char = 8 elif char in ['W','X','Y','Z']: char = 9 return char main() 方法将其返回。

join()

如果您不能使用def check_number(user_number): try: r = '' for char in user_number: if char.isalpha(): result = convert_to_num(char) r += str(result) else: r += char return r except Exception as err: print(err)

{{1}}

答案 1 :(得分:0)

此代码:

if char.isalpha():
    result = convert_to_num(char)
    return result
else:
    return char

将立即返回 ,并返回一个数字。您想返回字符串的 all 的所有数字,而不仅仅是返回第一个数字,因此您需要存储输出数字并最终将所有数字(在for循环完成之后)全部返回为单个数字字符串。

初始化一个空列表output = []并在for循环的每次迭代之后将输出数字附加到它之后,然后返回联接列表(使用"".join())是实现此目的的一种好方法。

如果不允许使用"".join(),也可以只构建一个字符串(output = ""output += char)并直接返回它,但这会比较慢。 / p>