【问题标题】:Split function not returning anything拆分函数不返回任何内容
【发布时间】:2022-01-09 06:34:57
【问题描述】:

我正在尝试创建一个命令行,但是当我使用 split 函数并打印它时,它返回 [],当我将它放入一个 if 语句中说 IndexError: list index out of range 时它返回一个错误。

这是我的代码:

rep = "repeat"
cmd = ""
errorColor = "\033[1;31;47m "
splitCmd = []


def cmdIn():
    cmd = input(">>")
    splitCmd = cmd.split()

cmdLen = len(cmd)
while True:
    cmdIn()
    print(splitCmd)
    if cmd == None:
        print("Error: no command entered")
    if splitCmd[0] == rep: 
        cmdArgs = ""
        for x in splitCmd:
            if splitCmd[1] == rep:
                print()
            else:
                cmdArgs += x+" "
                
    else:
        print("Unknown error")

谢谢,NDev

【问题讨论】:

  • 你必须从splitCmd函数返回splitCmd,否则......你将一无所有......
  • 您实际上有 两个 名为 splitCmd 的独立变量。一种是全局的,一种是cmdIn() 函数的本地。它们彼此没有影响。
  • ^^ cmd 也是如此。
  • @John Gordon - 它已经是公开的,它是在开头声明的
  • cmdIn() 中的变量是局部变量,因为 1)您分配给它,并且 2)您没有明确声明它是全局的。这就是 Python 的工作原理。

标签: python string list cmd split


【解决方案1】:

你需要在函数中返回splitCmd,然后在你的循环中调用

rep = "repeat"
cmd = ""
errorColor = "\033[1;31;47m "
splitCmd = []


def cmdIn():
    cmd = input(">>")
    splitCmd = cmd.split()
    return splitCmd
cmdLen = len(cmd)
while True:
    splitCmd = cmdIn()
    print(splitCmd)
    if cmd == None:
        print("Error: no command entered")
    if splitCmd[0] == rep: 
        cmdArgs = ""
        for x in splitCmd:
            if splitCmd[1] == rep:
                print()
            else:
                cmdArgs += x+" "
                
    else:
        print("Unknown error")

【讨论】:

  • 非常感谢,成功了
猜你喜欢
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2017-06-23
  • 2016-08-10
  • 2022-01-12
  • 2020-01-10
  • 2021-07-23
相关资源
最近更新 更多