2013-03-17 40 views
1

我試圖讓下面的代碼工作,它應該從用戶輸入的文本字符串中刪除元音。str.replace問題

def isVowel(text): 
    if text in ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U"): 
     return True 

def withoutVowels(text): 
    for char in text: 
     if(isVowel == True): 
      text = text.replace(char, "") 
    return text 

isVowel函數工作正常,但它似乎沒有正確評估時,我使用它,爲什麼?

+0

什麼是當它不能正常工作? – Xymostech 2013-03-17 01:25:25

+1

注意:'''''''''''''''''''' without_vowles = re.sub('[aeiou]','',text,flags = re.IGNORECASE)'或're.sub('[aeiouAEIOU]','',text)'。 – EOL 2013-03-17 01:38:32

回答

11
if (isVowel == True): 

應該是

if isVowel(char): 

isVowel是一個功能對象。 isVowel == True將始終爲False。


請注意,您也可以使用str.translate更快,更簡單地做到這一點。

In [90]: 'Abracadabra'.translate(None, 'aeiouAEIOU') 
Out[90]: 'brcdbr' 

,或(如EOL指出)使用正則表達式:

In [93]: import re 
In [95]: re.sub(r'(?i)[aeiou]', '', 'Abracadabra') 
Out[95]: 'brcdbr' 

然而,str.translate在這種情況下更快:

In [94]: %timeit 'Abracadabra'.translate(None, 'aeiouAEIOU') 
1000000 loops, best of 3: 316 ns per loop 
In [96]: %timeit re.sub(r'(?i)[aeiou]', '', 'Abracadabra') 
100000 loops, best of 3: 2.26 us per loop 
1

您可以在同一行做到這一點,因爲Python很棒:

def withoutVowels(text): 
    return "".join(c for c in text if c not in "aeiouAEIOU")