【问题标题】:Store integers in an input, separately to characters将整数存储在输入中,与字符分开
【发布时间】:2016-01-11 21:41:21
【问题描述】:

基本上,我正在创建一个将电话号码转换为 输入的字母,只是简单的数字。我已经设法做到这一点, 但是,如果您输入数字,它们将被删除,并且只有转换后的 字母被退回。

例如,如果您输入1800BUYNOW,而不是返回1800289669, 它只返回289669

有什么帮助吗?

#phone number converter
#v0.8
#this will convert phone numbers with letters in, into just phone numbers
#i.e. 1800BUYNOW should output as 1800289669

import time
import string

dicti = []

#######################################################################

def translate():
    print('Welcome to the telephone unconfuzzler!')
    num = input('''Type the number you which to deconfuzzle.
''')
    for char in (num):
        if char in ['A','B','C']:
            dicti.append(2)
        if char in ['D','E','F']:
            dicti.append(3)
        if char in ['G','H','I']:
            dicti.append(4)
        if char in ['J','K','L']:
            dicti.append(5)
        if char in ['M','N','O']:
            dicti.append(6)
        if char in ['P','Q','R','S']:
            dicti.append(7)
        if char in ['T','U','V']:
            dicti.append(8)
        if char in ['W','X','Y','Z']:
            dicti.append(9)
    finish()

#######################################################################

def finish():
     time.sleep(0.5)
     print('''Converting
...''')
     time.sleep(1)
     print('''Here is your deconfuzzled number:''')
     print (*dicti, sep='')
     end()

#######################################################################

def end():
    conta = input('Would you like to convert another number?')
    if conta in ['y', 'Y', 'yes', 'Yes', 'YES']:
        translate()
    elif conta in ['n', 'N', 'no', 'No', 'NO']:
        conta2 = input('Are you sure you would like to quit?')
        if conta2 in ['y', 'Y', 'yes', 'Yes', 'YES']:
            exit()
        elif conta2 in ['n', 'N', 'no', 'No', 'NO']:
            end()


#######################################################################

translate()

【问题讨论】:

    标签: python python-3.x list input phone-number


    【解决方案1】:

    只需替换

       if char in ['A','B','C']:
    

       if char in ['A','B','C','1']:
    

    等等。

    实际上你应该在结尾加上一个 else 来报告未知字符并将 if 替换为 elifs。

    【讨论】:

    • 谢谢伙计,只是一个初学者!现在我有一个问题,如果他们回答是输入一个新号码,我需要清空旧号码的字典列表,有什么帮助吗?
    • 其实在你当前的代码中你需要。但是,如果 dicti 是 translate 函数的局部变量并且您返回计算值会更干净
    • 你有机会展示你想要的吗?我是一个真正的菜鸟。我了解全局变量和局部变量是什么,但我不确定是否会在定义它的函数之外返回一个。
    • 不想窃取学习经验。在这里你可以找到一个很好的解释learnpythonthehardway.org/book/ex21.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2014-07-29
    • 1970-01-01
    相关资源
    最近更新 更多