Python 3.2“;类型错误:Can';t转换为';类型';隐式地反对str”;

Python 3.2“;类型错误:Can';t转换为';类型';隐式地反对str”;,python,string,function,printing,echo,Python,String,Function,Printing,Echo,我得到一个错误,我不知道如何完善我的代码 基本上,我要做的是在终端应用程序中使用伪echo命令 while True: foo = input("~ ") bar = str if foo in commands: eval(foo)() elif foo == ("echo "+ bar): print(bar) else: print("Command not found") 显然,它不起作用 有人知道

我得到一个错误,我不知道如何完善我的代码

基本上,我要做的是在终端应用程序中使用伪
echo
命令

while True:
    foo = input("~ ")
    bar = str
    if foo in commands:
        eval(foo)()
    elif foo == ("echo "+ bar):
        print(bar)
    else:
        print("Command not found")
显然,它不起作用


有人知道我需要用什么来完成这个项目吗?

这段代码可能会给你带来问题:

"echo "+ bar
bar
等于
str
,这是一种数据类型

下面是我如何修复您的代码:

while True:
    command = input("~ ")    # Try to use good variable names

    if command in commands:
        commands[command]()  # Avoid `eval()` as much as possible.
    elif command.startswith('echo '):
        print(command[5:])   # Chops off the first five characters of `foo`
    else:
        print("Command not found")

创建一个变量
bar
,并将其设置为
str
,即字符串类型。然后尝试将其添加到字符串
“echo”
。这显然行不通。您想用
做什么<代码>栏
未连接到用户输入,因此无论用户类型如何,它都不会更改

如果要查看输入是否以“echo”开头,然后打印其余内容,可以执行以下操作:

if foo.startswith("echo "):
    print foo[5:]

str
不表示“任何字符串”;这是所有字符串的类型。您应该阅读以熟悉Python的基础知识。

请给出完整的错误消息。还有,你希望这段代码做什么?我想做的是,如果输入是“echo”+(任何字符串),打印(字符串)啊,这很好,我第一次读错了,因为有人在分散我的注意力,非常感谢!我想,如果我将bar指定为字符串,它可能会工作,但显然我没有尝试您的方法,但我得到了以下结果:主命令[command]()第19行的文件“/shell.py”类型错误:列表索引必须是整数,而不是str