2016-08-17 144 views
0

好吧,我正在製作一個編碼器/解碼器,目前我正在測試以查看我的想法是否可行,但我不斷收到錯誤,告訴我我的字符串索引超出範圍,當它不應超出範圍首先。索引錯誤:字符串超出範圍,但它不應超出範圍?

message = "abc" 
#Should come out as 212223 
translated = ' ' 


n = 1 
while n >= 0: 
    t = message[n] 
    if t == 'a': 
     translated = translated + '21' 
    elif t == 'b': 
     translated = translated + '22' 
    elif t == 'c': 
     translated = translated + '23' 
    while n <= len(message): 
     n = n + 1 
print(translated) 

這讓我感覺良好,所以我有一個很難尋找能解決我在做什麼適當的幫助,所以我可以有一些幫助?一個鏈接,一個解決方案,我做錯了什麼以及如何解決它?謝謝

回答

3
n = 0 
while n >= 0: 

你有一個無限循環,你繼續增加n。 在某一點message[n]將超出範圍。

您應該將while n <= len(message):作爲您的主循環而不是當前的循環。

一個更好的辦法,是在messagefor循環直接迭代:

for t in message: 
    if t == 'a': 
     translated = translated + '21' 
    elif t == 'b': 
     translated = translated + '22' 
    elif t == 'c': 
     translated = translated + '23' 
0

這裏:

while n <= len(message): 
    n = n + 1 

如果需要更改爲:

while n < len(message): 
    n = n + 1 

的最後一個索引的字符串將爲len(message) - 1,因爲索引編制從0. 但是,我會立即將n設置爲len(message) - 1。

0

因爲在最後一個循環中,您正在使用t = message [3] ..這是您錯誤的原因。如果消息變量包含「abc」,則只能訪問t = message [0],t = message [1],t = message [2]。所以試試這個

message = "abc" 
#Should come out as 212223 
translated = ' ' 


n = 1 
while n >= 0: 
    t = message[n-1] 
    if t == 'a': 
     translated = translated + '21' 
    elif t == 'b': 
     translated = translated + '22' 
    elif t == 'c': 
     translated = translated + '23' 
    while n <= len(message): 
     n = n + 1 
print(translated)