2012-10-06 126 views
0

我收到一個錯誤,我不知道如何優化我的代碼。Python 3.2「TypeError:無法將'type'對象隱式轉換爲str」

基本上,我想要做的是在終端應用程序中僞echo命令。

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

很明顯,它不工作。

有沒有人知道我需要用什麼來完成這個項目?

+2

請給出完整的錯誤信息。另外,你期待這個代碼做什麼? – BrenBarn

回答

2

您創建一個變量bar並設置它等於str,這是字符串類型。然後嘗試將其添加到字符串"echo "。這顯然是行不通的。你想用bar做什麼? bar沒有連接到用戶輸入,所以無論用戶輸入什麼內容,它都不會改變。

如果你想看看如果輸入開頭爲「回聲」,然後如果是打印的休息,你可以這樣做:

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

str並不意味着「任何字符串」;這是所有字符串的類型。您應該閱讀the Python tutorial以熟悉Python的基礎知識。

+0

我想要做的是,如果輸入是「回聲」+(任何字符串),打印(字符串) – ever99

+0

@TimothyDuane:請參閱我編輯的答案。 – BrenBarn

+0

啊,這個工作完美,我第一次讀錯了,因爲有人讓我分心,非常感謝! – ever99

0

此代碼可能是給你的問題:

"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") 
+0

我想如果我將bar指定爲字符串,它可能工作但顯然沒有 – ever99

+0

@TimothyDuane:請參閱我的編輯。我已經添加了一些東西 – Blender

+0

我試過你的方法,但是我得到了這個: 文件「./shell.py」,第19行,主要在 命令[command]() TypeError:列表索引必須是整數,不str – ever99

相關問題