2017-08-15 13 views
-4

我剛開始Python和我被困在一個愚蠢的錯誤,但我不明白爲什麼它不工作問:python:爲什麼我的char被視爲str?

def encryption(str1): 
    i = 0 
    for x in str1: 
     if (x >= 'a' and x <= 'z' or x >= 'A' and x <= 'Z'): 
      str1[i] = str1[i] + 3 % 26 #str[i] = x + 3 % 26 
     i+=1 
    return str1 

當我執行該程序,我得到這個錯誤:

TypeError: string indices must be integers, not str.

燦有人向我解釋爲什麼str [i] - 23被認爲是str?對我來說,我只是修改了char的ascii值。

+2

這不是C,嘗試'ORD(STR1 [I])'得到ASCII字符的值。爲什麼混合指數與'x'?並且錯誤似乎在其他地方... –

+0

並在發佈之前修復您的縮進。 –

+0

請記住,字符串是immutable –

回答

1

python中的字符串不是像C中的數組。它們是不可變的,即 您無法對字符串進行適當的更改。你的選項是將 這個字符串轉換成一個列表(類似於一個c數組)或者創建一個新的空字符串 並將每個加密的字母連接到它(這可能會更快)。 Ord將字符串轉換爲ascii數字並且chr轉換反轉。 的因而isalpha方法測試真當且僅當該字符是在{A-Z A-Z}

str1 = 'this is a test [email protected]#[email protected]#[email protected]' 

def encryption(str1): 
    new_string = '' 
    for character in str1: 
     if character.isalpha(): 
      new_string += chr(ord(character) + 3 % 26) 
     else: 
      new_string += character 
    return new_string 

print(encryption(str1)) 
+0

噢好吧,以及我認爲我會做一個大蟒蛇字符串訓練會話,但我沒有注意到python和C字符串之間的差別很大。好吧,謝謝。 – Cjdcoy

+0

主要的區別是不可抵抗性。您可以索引字符串,就像在C中一樣,但不能更改單個字符元素。如果你想把它變成一個僞C數組,做一個列表理解數組= [[x for string in string]],然後在使用「」.join(array)後修改它。雖然,我的答案中的方法將更快,更pythonic。 – Rosh

+0

是的我沒有做python模仿c,所以我會嘗試像你一樣推理。 – Cjdcoy

相關問題