2015-09-26 81 views
2

目的是從輸入刪除元音在if語句中使用「not in」時出現Python錯誤?

我的代碼

def anti_vowel(text): 
    av=[] 
    for t in range(len(text)): 
    if t not in "aeiouAEIOU": 
     av.append(text[t]) 
    print "".join(av) 
anti_vowel("Hey You!") 

錯誤:

Traceback (most recent call last): 
File "prog.py", line 7, in <module> 
File "prog.py", line 4, in anti_vowel 
TypeError: 'in <string>' requires string as left operand, not int 

請給出一個理由,爲什麼這是行不通的

+2

你只是想'在文叔:',它會遍歷text'的'字符。 – ekhumoro

+0

添加'print t'會在幾秒鐘內發現問題。 – kindall

回答

3

這是因爲變量t的值是一個整數,而不是一個字符串。

range(len(text))返回[0, 1, 2, 3, 4, 5, 6, 7]

當您遍歷range(len(text))時,t的值是一個整數,該值用於執行not in檢查,因此是錯誤。

您可以改爲改寫text而不是range(len(text))

def anti_vowel(text): 
    av=[] 
    for t in text: 
     if t not in "aeiouAEIOU": 
      av.append(t) 
    print "".join(av) 

anti_vowel("Hey You!") 
4

當你做range(len(text))你正在構造輸入字符串text的長度範圍。所以t的值是整數0, 1, 2... len(text)-2, len(text)-1

什麼你可能想要做的是遍歷字符串本身中的字符:

for t in text: 
    if t not in "aeiouAEIOU": 
     av.append(t) 
1

第4行中,應該有,而不是數字索引t字符text[t]。這將修復你的代碼。

Python可以爲您處理索引。 全功能可寫,然後在短短一個易於閱讀的路線:

print "".join(ch for ch in text if ch not in 'aeiouAEIOU')