2015-10-17 89 views
-1

因此,假設我已經定義了一個名爲vowel_call的函數,它只從字符串中繪出元音,我如何將此函數集成到另一個名爲nonvowels的函數中,以便從一般字符串?功能:返回非元音字符串

def nonvowels (word: str) -> str: 
    result = '' 
    for x in word: 
    if vowel_call(x) == False: 
     result = result + x 
     return result 
assert nonvowels('book') == 'bk' 
assert nonvowels('giraffe') == 'grff' 

我試圖代碼沒有斷言語句和Python只給後面的詞組的第一個nonvowel:(nonvowels( '精靈')= 'G'),而不是 'GN'。使用assert語句,會產生錯誤。我應該怎麼做來修復代碼?

+0

「vowel_call從字符串引出只有元音」 - 笏? –

回答

0

您的函數返回的時間太早。將return聲明中的縮進減少到循環外

0

是否在您的if語句中使用了return語句?如果是這樣,這可能是您僅返回第一個非元音字母的問題嗎?只有當字母不是元音時,vowel_call方法纔會返回false嗎?看看第一個建議,如果這不是你的問題,請告訴我。

0

您正在第一次回到循環中if vowel_call(x) == False的計算結果爲True,您需要在檢查字符串中的每個字符後將循環移回循環外。

但最簡單的方法是返回一個列表理解str.join

def nonvowels (word: str) -> str: 
    return "".join([x for x in word if not vowel_call(x)]) 
0
You can also with set operations find what you need. 

sentence = 'It is a nice day!' 

def find_vowels(s,): 
import re 
s = s.lower() 
return set(re.findall(r'[aoiue]',s)) 

>>>find_vowels(sentence) 
{'a', 'e', 'i'} 

s_sentence = set(sentence.lower()) 

>>>non_vowels = s_sentence - find_vowels(sentence) - set(string.punctuation) - set(string.whitespace) 

{'c', 'y', 'n', 't', 's', 'd'} 
+0

當OP在預期輸出中有重複值時,您將如何使用一個集合? –