python - 如何在Python中获取多个字符输入并对其进行处理

标签 python

我需要一个程序,从用户(文本)获取 1 行输入,然后将输出作为文本(我在下面写一个示例)

我尝试过if,但它只接受一行代码,如果我写了一个未定义的单词,它就会破坏其余的代码。

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

谢谢。

最佳答案

我们可以使用 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

关于python - 如何在Python中获取多个字符输入并对其进行处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55674417/

相关文章:

python - 从字符串中提取单词以创建特征集 nltk

python - 如何重新运行已经使用 TriggerDagrunoperator 执行的 dag?

python - HttpResponse(status=<code>) 如何在 Django 中工作?

python - 图形学 : how to color nodes using values from a column

python - 按日期和时间查询存储在 MongoDB 中的数据

python - 在单线程 Python 应用程序中关闭 socketserver serve_forever()

python - 从单个 python 脚本或 GUI 按钮运行服务器和客户端 python 脚本

python - BeautifulSoup 标签的出现顺序

python - 在模块中实例化一个类

python - 根据字符串文字从联合类型创建数据类实例