如何在Python中获得多个字符的输入并对其进行处理

2024-10-02 20:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个程序,从用户(文本)获得一行输入,然后以文本形式输出(我在下面写了一个例子)

我尝试了如果但是它只接受一行代码,如果我写了一个没有定义的单词,它会毁了其他的。你知道吗

class meaning():
  def shortcutA (self):
    print ("ice cream")
  def shortcutB (self):
    print ("Choclet cake")

def main():
    m = meaning()

    if input() == "a":
      print("your code is: ")
      m.shortcutA()
    elif input() == "b":
      print("your code is: ")
      m.shortcutB()
    else :
      print ("unrecognized")

print ("Please enter the words :")

if __name__ == "__main__":
  main()

我希望当我进入a b时,结果是

ice cream 
Choclet cake

谢谢你。你知道吗


Tags: 文本selfinputyourifmaindefprint
3条回答

我建议这样的计划

class meaning():
    def shortcutA(self):
        return "ice cream"

    def shortcutB(self):
        return "Chocolet cake"


def main():
    m = meaning()
    code = ''
    for alphabet in user_input:
        if alphabet == "a":
            code += ' ' + m.shortcutA()
        elif alphabet == "b":
            code += ' ' + m.shortcutB()
    if len(code) == 0:
        print 'Unrecognized.'
    else:
        print 'The code is : ' + code


user_input = raw_input('Please enter the words : \n')

if __name__ == "__main__":
    main()

您需要修改if输入语句。 如果要根据空格分隔的输入输出,请使用以下命令:

for x in input():
    if(x=='a'):
         print(m.shortcutA(),end=' ')
    if(x=='b'):
         print(m.shortcutB(),end=' ') 
    else:
         print('unrecognised!')

希望这有帮助。。你知道吗

我们可以使用for循环遍历单词中的输入。你知道吗

class meaning():
  def shortcutA (self):
    print ("ice cream")
  def shortcutB (self):
    print ("Choclet cake")



def main():
    m = meaning()
    print_flag = False
    for i in input():
        if i in ['a', 'b'] and not print_flag:
            print("your code is: ")
            print_flag = True
        if i == "a":
            m.shortcutA()
        elif i == "b":
            m.shortcutB()
        elif i == ' ':
            continue
        else :
             print ("unrecognized")

print ("Please enter the words :")

if __name__ == "__main__":
  main()

产生:

Please enter the words :
your code is: 
ice cream 
Choclet cake

相关问题 更多 >