因此,我目前正在處理的腳本的一部分是由幾個單詞組成的列表。我希望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只記下每個單詞的長度?我無法想出辦法。
Python列表索引是從零開始的。如果列表中有五個項目,則有效索引是'item [0]'到'item [4]'。 –