2013-05-06 91 views
1

我正在爲計算機科學類創建一個項目,其中創建了一個堆棧密碼。我正在使用複製到剪貼板功能,以便允許通過下一個密碼更改消息。我遇到了第二個密碼的問題,這是一個替代密碼。當我運行它時,它會返回一個「無法將int'隱式轉換爲str」。我曾嘗試使用str(消息),但不起作用,我試圖改變代碼。我對python不太好,所以如果這是一個簡單的錯誤,請告訴我。我能做些什麼來幫助解決這些錯誤。我曾想過將消息更改爲列表,但我該怎麼做?無法將int轉換爲str

這裏是我使用的代碼:

def main(): 
    myMessage = pyperclip.paste() 
    myKey = 8 
    ciphertext = encryptMessage(myKey, myMessage) 
    print(ciphertext + '|') 
    pyperclip.copy(ciphertext) 
def encryptMessage(key, message): 
    ciphertext = [''] * key 
    str(ciphertext) 
    for col in range(key): 
     pointer = col 
     while pointer < len(message): 
      ciphertext[col] += message[pointer] 
      pointer += key 
    return ''.join(ciphertext) 
    print(ciphertext) 

,這裏是錯誤我收到:

Traceback (most recent call last): 
    File "I:\project\transpositionEncrypt.py", line 38, in <module> 
    Enc() 
    File "I:\project\transpositionEncrypt.py", line 37, in Enc 
    main() 
    File "I:\project\transpositionEncrypt.py", line 10, in main 
    ciphertext = encryptMessage(myKey, myMessage) 
    File "I:\project\transpositionEncrypt.py", line 27, in encryptMessage 
    ciphertext[col] += message[pointer] 
TypeError: Can't convert 'int' object to str implicitly 

回答

2

嘗試

ciphertext[col] += str(message[pointer]) 

此異常告訴你,這是不願意將整數轉換爲字符串,也就是說,它不願意將"foo" + 1評估爲"foo1"。要做到這一點,你必須明確地轉換爲一個字符串。這是Python設計者反覆選擇的選擇,它支持顯式隱式語義。

0

所以,既然你不能隱式地做,明確地做!

ciphertext[col] += str(message[pointer]) 
0

對我的作品。我複製你的代碼,它沒有任何問題......你用什麼版本Pyperclip的,哪些版本的Python?