2016-10-26 20 views
-1

因此,我目前正在處理的腳本的一部分是由幾個單詞組成的列表。我希望Python能夠逐個循環單詞並反轉每個單詞。我的腳本不斷返回IndexError:字符串索引超出範圍

我試圖做這樣說:

假設我輸入 '你好世界,這是一個Python腳本'

def main(): 
    print() 
    ptext = input('Please input the plaintext...') 
    ctext = '' 
    plist=ptext.split(' ') 
    for item in plist: 
     i = len(item) 
     while i>=0: 
      ctext = ctext + str(item)[i] 
      i=i-1 
    print() 
    print('The ciphertext is: ',ctext.lower()) #Print out the ciphertext 
    print() 

但我不斷收到:

Traceback (most recent call last): 
    File "<pyshell#137>", line 2, in <module> 
    print((item)[i],end =(' ')) 
IndexError: string index out of range 

我清楚告訴腳本i=len(item),那怎麼會超出範圍?

我最好的和唯一的猜測是,它採用的是像'世界'這樣的單詞的長度,它是5並且用在'is'或'a'這樣的單詞上。是否有可能告訴Python只記下每個單詞的長度?我無法想出辦法。

+1

Python列表索引是從零開始的。如果列表中有五個項目,則有效索引是'item [0]'到'item [4]'。 –

回答

3

一個字符串的第一個指數是0,最後是「的長度 - 1「。所以你需要設置i = len(item) - 1,因爲在第一次迭代中,你基本上試圖訪問str(item)[len(item)]

除此之外,str()呼叫應該沒有必要,所以只是item[i]

另請注意,如果你想「反轉」一個字符串,你實際上可以做reversed_string = original_string[::-1][::-1]表示它應該返回字符串,但從結尾開始並且開始一個字符。

+0

非常感謝您花時間回答!而你的建議很有效 – scripter

4

替換:

ctext = ctext + str(item)[i] 

與:

ctext = ctext + str(item[i]) 
#      ^access index of item 

而且,初始化i爲:

i = len(item) - 1 # because index starts with 0, and can be retrieved till `len - 1` 
+1

'item [i]'仍然超出範圍,因爲'i = len(item)'。 –

+0

@JohnGordon:是的。你是尖銳的觀察者;)。更新它。 –

+0

更好的是,完全刪除'str'。 –

相關問題