2015-10-05 47 views
2

我想寫一個簡短的腳本,將一個單詞或句子轉換成它的字母值,然後跳轉5個值,然後打印結果爲一個字符串。 例如Python 3.x:AttributeError:'str'對象沒有屬性'追加'

['a', 'b', 'c'] 

應更改爲...

'102 103 104' 

不過,我只得到了上面的錯誤。 有問題的代碼:

def enc(input, output, seq, str_int): 
    input = input.lower() 
    output = [] 
    for char in input: 
     num = ord(char) + 5 
     str_int = str(num) 
     output.append(str_int) 
     output = seq.join(output) 
    return output 
print(enc("hello", [], ' ', ' ')) 

我敢肯定,我只是失去了一些東西真的很明顯。謝謝。

+0

正在轉換'輸出= seq.join(輸出)'輸出字符串,它是問題發生的原因 – The6thSense

+0

是的,它原本是一個列表,但後來改爲字符串打印。 –

+1

它應該用return語句直接縮進,或者你可以刪除'output = seq.join(output)'並鍵入'return seq.join(output)'你的問題是由於縮進錯誤 – The6thSense

回答

2

問題的發生是因爲線路 -

output = seq.join(output) 

根據壓痕,這是for循環內,因此裏面的for循環中,要更改output變量str(串),之後當你嘗試做output.append()時,它出錯了。這是問題的主要原因。

我猜你實際上只打算在循環外完成output列表。但是,你真的不需要設置回來,你可以簡單地做 -

def enc(input, output, seq, str_int): 
    input = input.lower() 
    for char in input: 
     num = ord(char) + 5 
     str_int = str(num) 
     output.append(str_int) 
    return seq.join(output) 

演示 -

>>> def enc(input, output, seq, str_int): 
...  input = input.lower() 
...  for char in input: 
...   num = ord(char) + 5 
...   str_int = str(num) 
...   output.append(str_int) 
...  return seq.join(output) 
... 
>>> print(enc("hello", [], ' ', ' ')) 
109 106 113 113 116 
+0

我現在意識到自己的錯誤。再次感謝。 :) 我會接受你的答案,但計時器是一件事情。 –

+0

很高興我能幫到你。我相信你現在可以接受答案。計時器是15分鐘:) –

相關問題