1

I have a string name = "Aaron" and would like to remove all the vowels. I am using remove() but if the char is repetive like letter 'a' in this case it stays in the string. Any suggestions ? Here is my code :

def disemvowel(word):
    word_as_list = list(word.lower())
    print(word_as_list)
    vowels = ["a", "e", "i", "o", "u"]
    for char in word_as_list:
        for v in vowels : 
            if char == v : 
                word_as_list.remove(v)
    return "".join(word_as_list)

print(disemvowel("Aaaron"))
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
  • `word = "".join([c for c in word if c.lower() not in "aeiou"])` – Spherical Cowboy Mar 28 '17 at 11:24
  • This is not the case. – Spherical Cowboy Mar 28 '17 at 11:29
  • You can efficiently remove (or modify) multiple characters in a _string_ with the [`translate`](https://docs.python.org/3/library/stdtypes.html#str.translate) method. Eg, `novowels = {ord(c): None for c in 'AEIOUaeiou'}; my_string.translate(novowels)` – PM 2Ring Mar 28 '17 at 11:31
  • 5
    BTW, I _love_ your function name. :) – PM 2Ring Mar 28 '17 at 11:36
  • FWIW, another way to make the translation table is `novowels = str.maketrans('','','AEIOUaeiou')`. See the second linked question above for more details. – PM 2Ring Mar 28 '17 at 11:42
  • Thanks guys . I wasn't aware of list comprehension. Seems to be a very elegant and natural to read approach. – Ivan Ivanov Mar 28 '17 at 11:54
  • List comprehensions are awesome. They're an essential item in the Python toolkit. There are also dict and set comprehensions. And then there are generator expressions which are similar to list comprehensions, except they allow you to iterate over a sequence of items without having to create the sequence in RAM. – PM 2Ring Mar 28 '17 at 12:01
  • Giving an alternate, working solution does nothing to help OP understand why his approach doesn't work. Teach people why, don't hand out answers with no explanation. – Josh J Mar 28 '17 at 12:51

1 Answers1

0

As other people have said, list comprehension is the way to go:

def disemvowel(word):
    word = word.lower()
    vowels = ["a" , "e", "i", "o", "u"]
    return "".join([char for char in word if char not in vowels])  
print disemvowel("Aaaallbag")
Keef Baker
  • 641
  • 4
  • 22
  • 1
    This technique is great for a general list, but to delete or replace characters in a string the `.translate` method is _much_ faster because it does the looping and processing with compiled code, so it runs at C speed. FWIW, an alternate list comp approach is `d = dict.fromkeys('AEIOUaeiou', ''); newdata = ''.join([d.get(c, c) for c in data])`. – PM 2Ring Mar 28 '17 at 11:58
  • This answer will lowercase any consonant that may have been uppercase. That may not be what you want. – Josh J Mar 28 '17 at 12:54
  • Yep. It's what the OP was doing, so I followed suit with what he wanted. – Keef Baker Mar 28 '17 at 12:58