我建立了這個函數來改變一個字符串輸入到拉丁語中。我試圖檢查索引是否超出範圍,但是我的檢查方法是讓索引超出範圍。我試圖檢查索引是否超出範圍,但我使用的代碼是索引超出範圍?
見如下:
def simple_pig_latin(input, sep=' ', end='.'):
words=input.replace(" ", " ").split(sep)
new_sentence=""
Vowels= ('a','e','i','o','u')
Digit= (0,1,2,3,4,5,6,7,8,9)
cons=('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z')
characters= ('!','@','#','$','%','^','&','*','.')
for word in words:
if word[0] == " ":
new_word=word
else:
if word[0] in Vowels:
new_word= word+"way"
if word[0] in Digit:
new_word= word
if word[0] in cons:
first_letter=word[0] #saves the first letter
change= str(word) #change to string
rem= change.replace(first_letter,'')
put_last= rem+first_letter #add letter to end
new_word= put_last+"ay"
if word[0] in characters:
new_word= word
new_sentence= new_sentence+new_word+sep
new_sentence= new_sentence.strip(sep)+end
return new_sentence
你可以看到第一個if語句檢查,如果它是空的,但我得到這個確切的錯誤:
「9號線IndexError:字符串索引出的範圍「
我還可以檢查空序列嗎?我不能用範圍內的單詞(len(words)),因爲那麼我的if語句都不起作用。它會告訴我對象不是可下載的。
「你可以看到第一個if語句是檢查它是否爲空「 - 不,它不是。它試圖訪問「word [0]」,看看「word [0]」是否是一個空格。它假定存在「word [0]」。這不像檢查'word'是否爲空。 – user2357112
這個問題被低估的原因是什麼?我想解決我的錯誤,以便它不會得到可憐的選票。 –