-4

I wrote this function in Python which takes string as an input and the outputs the same string with all chars in lower case, with vowels removed. It's not working as expected, why is that?

def removingVowels(string):
    string.lower()
    vowels = ['a','e','i','o','u']
    for char in string:
        if char in vowels:
            del string[char]
    return string
    print (removingVowels("HadEEl"))
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Hadeel36
  • 83
  • 1
  • 1
  • 8

1 Answers1

0

Strings are immutable in Python, so you cannot delete a character from them. You need to create a new string.

You would do something like this:

>>> def removingVowels(string):
...    string=string.lower()
...    return ''.join([c for c in string if c not in 'aeiou'])
... 
>>> removingVowels("HadEEl")
'hdl'

How it works:

  1. string=string.lower() You need to assign the result of the string.lower() back to string. It is a common error in Python not to do that.
  2. We then have a list comprehension that interates over the string character by character. The list comprehension builds a list of each character unless it is a member of the string 'aeiou'
  3. The list needs to be joined character by character to form a new string. That is then retuned.
dawg
  • 98,345
  • 23
  • 131
  • 206