string - Filtering objects from lists in python -
i'm trying program filter vowels out of string of text , i'm not sure why function doesn't work. here's code
def anti_vowel(text): letters = text.split() #make list of letters in string index = 0 #for del x in letters: if x == "a" or x == "a" or x == "u" or x == "u" or x == "i" or x == "i" or x == "o" or x == "o" or x == "e" or x == "e": del letters[index] index += 1 #to make if-clause work return "".join(letters) #turn edited list string
while iterating on letters if-clause should activated when object in letters vowel right? should delete object. doing wrong?
your code isn't iterating through letters, it's iterating through words. because text.split()
splits text list
of whitespace-separated "word" strings.
the next problem you're iterating through list
, deleting entries. mutating iterable while iterating through common cause of strange results.
instead, this:
def anti_vowel(text): return ''.join(filter(lambda x: x.lower() not in 'aeioe', text))
result:
>>> anti_vowel('hi name joe') 'h nm s j'
Comments
Post a Comment