【问题标题】:Python 3.2 "TypeError: Can't convert 'type' object to str implicitly"Python 3.2“TypeError:无法将'type'对象隐式转换为str”
【发布时间】:2012-10-06 05:14:43
【问题描述】:

我收到一个错误,我不知道如何优化我的代码。

基本上,我想做的是终端应用程序中的伪echo 命令。

while True:
    foo = input("~ ")
    bar = str
    if foo in commands:
        eval(foo)()
    elif foo == ("echo "+ bar):
        print(bar)
    else:
        print("Command not found")

显然,它不起作用。

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

【问题讨论】:

  • 请给出完整的错误信息。另外,您希望这段代码做什么?

标签: python string function printing echo


【解决方案1】:

您创建一个变量bar 并将其设置为等于str,即字符串类型。然后您尝试将其添加到字符串"echo "。这显然行不通。你想用bar 做什么? bar 没有连接到用户输入,所以无论用户输入什么,它都不会改变。

如果您想查看输入是否以“echo”开头,然后打印其余部分,您可以这样做:

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

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

【讨论】:

  • 我想要做的是如果输入是“echo”+(任何字符串),打印(字符串)
  • 啊,这很好用,我第一次读错了,因为有人分散了我的注意力,非常感谢!
【解决方案2】:

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

"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 指定为字符串,它可能会起作用,但显然没有
  • 我试过你的方法,但我得到了这个:文件“./shell.py”,第 19 行,在主要命令[command]() TypeError: list indices must be integers, not str跨度>
猜你喜欢
  • 1970-01-01
  • 2020-02-24
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 2012-11-19
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多