【问题标题】:How to obtain the separate parts of a string when you don't know the amount of parts there will be当您不知道会有多少部分时,如何获取字符串的各个部分
【发布时间】:2017-05-20 13:25:05
【问题描述】:

我已经搜索和搜索,但没有找到我的应用程序

def getInput():
    command = input("What would you like to do now? ").split()
    verb_word = command[0]

    if verb_word in verbDict:   
        verb = verbDict[verb_word]
    else:      
        print('Unknown command: "{}"'.format(verb_word))
        print("The commands are:")        
        for i in len(verb_dict):
            print(verbDict[i])    

我已经有一个拆分,但我需要单独的部分,然后用它们调用一个具有多个参数但没有相同的函数。

【问题讨论】:

  • 这个问题不是特别清楚。你希望结果是什么?
  • @Metropolis 我正在尝试使用字符串的单独部分调用函数,即。 spam(var1, var2, var3) 或 spam2(var4)
  • 格式化/缩进有问题
  • 顺便说一句:你可以使用for word in verb_dict: print(word)而不是for i in len():(或者更确切地说是for i in range(len()):
  • 您可以尝试使用 argparse 模块,该模块通常用于命令行参数,但可以接受字符串。 Python网站有一个教程docs.python.org/3.6/howto/argparse.html#id1。不知道你是否会这么看。虽然矫枉过正。

标签: python string split


【解决方案1】:

我假设您正在接受看起来像这样的输入

command parameter another_parameter

你想最终得到类似的东西

verb_dict['command']('parameter', 'another_parameter')

你可以使用python的打包和解包来做到这一点

command, *parameters = input("What would you like to do now? ").split()

然后你有command = 'command'parameters = ['parameter', 'another_parameter']

然后您可以在字典中查找函数,然后将列表解压缩到函数调用中

verb_dict['command'](*parameters)

【讨论】:

  • 这仅适用于 Python 3(用于 command, *parameters 解包部分)。对于 Python 2,您需要 command, paramers = command[0], command[1:]
  • @brunodesthuilliers 我从input 的用法和print 函数中假设这是python 3
  • 我们经常看到 python 初学者(错误)使用 input()(而不是 raw_input() 并在使用 python2 时将括号添加到 print - 出于无知或因为他们在 python 3 教程中看到了这一点;-)
猜你喜欢
  • 2022-06-14
  • 2021-11-03
  • 2011-06-27
  • 1970-01-01
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多