-1
def disemvowel(string):
    vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
    listString = list(string)
    for t in listString:
        if t in vowels:
            listString.remove(t)
    string = ''.join(listString)
    return string

The function is supposed to remove all the vowels and if the input is:

'This website is for losers LOL!' 

The correct output should be:

'Ths wbst s fr lsrs LL!' 

But the moment I changed the input to have vowels appear consecutively with each other i.e.

'This websitea is for loosers LOL!' 

The output becomes

'Ths wbsta s fr losrs LL!' 

which is incorrect (see 'wbsta' and 'losrs').

MSeifert
  • 145,886
  • 38
  • 333
  • 352
ic3man
  • 7
  • 1

2 Answers2

4

Instead of removing the vowels, why not just construct the string from the characters that aren't vowels?

return ''.join([c for c in string if c not in vowels])
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Wouldn't a generator be preferable over a list comprehension? – Alexander Aug 29 '17 at 15:36
  • 1
    No for `join` a list comprehension is better because [`str.join` requires a sequence](https://github.com/python/cpython/blob/v3.6.2/Objects/unicodeobject.c#L9903) and would immediately convert it to a list (additional overhead) if it's not a sequence. – MSeifert Aug 29 '17 at 15:37
  • 1
    To add to @MSeifert comment, this is because behind the scenes, `str.join` converts the iterator passed in to a list. Passing in a generator would just create additional overhead. If your curious, the implementation details can be seen [here](https://github.com/python/cpython/blob/master/Objects/stringlib/join.h#L22). – Christian Dean Aug 29 '17 at 15:38
1

It's generally not a good idea to remove items from the thing you're iterating from, because this can cause implications during the iteration. Therefore, instead of removing the characters that are vowels from the string, instead add the characters that aren't vowels to a new string.

def disemvowel(string):
    vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
    listString = list(string)
    string = ""
    for t in listString
        if t not in listString
            string += t

    return string
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
user8478480
  • 427
  • 3
  • 13