简体   繁体   中英

Function: Returning a string of nonvowels

So assuming I've already defined a function called vowel_call that draws out only the vowels from a string, how do I integrate this function into another function called nonvowels to return a string of only nonvowels from a general string?

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'

I tried the code without the assert statements, and Python only gives back the first nonvowel of the phrase: (nonvowels('genie') = 'g'), but not 'gn'. With the assert statements, an error is produced. What should I do to fix the code?

Your function returns too early. Reduce the indent on the return statement to be outside the loop

Is your return statement inside of your if statement? If it is, could that be your problem for returning only the first non vowel letter? And does the vowel_call method return false only when the letter is not a vowel? Check out the first suggestion, if that's not your problem, let me know.

You are returning inside the loop the first time if vowel_call(x) == False evaluates to True, you would need to move your return outside the loop after you have checked every char in the string.

def nonvowels (word: str) -> str:
   result = ''
   for x in word:
       if vowel_call(x) == False:
           result = result + x
   return result # outside loop

But the simplest method is to return a list comprehension with str.join :

def nonvowels (word: str) -> str:
   return "".join([x for x in word if not vowel_call(x)])
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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM