Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove vowels from a string [duplicate]

I've tried to be as clear as possible in the title but it was kind of hard to explain it briefly. I have to remove all the vowels from a certain string; to do that, I made a loop that goes through a list composed of the characters of that string, removes the vowels and then joins them:

def anti_vowel(text):
    vow = ["a", "e", "i", "o", "u"]
    chars = []

    for i in text:
        chars.append(i)

    for i in chars:
        if i.lower() in vow:
            chars.remove(i)

    return "".join(chars)

The problem is that when I run the code there will always be a vowel that doesn't get deleted. Examples:

>>> anti_vowel("Hey look Words!")
Hy lk Words!

>>> anti_vowel("Frustration is real")
Frstrton s ral

I'm in no way an expert in Python but this is confusing. Why would it delete some letters and keep others, even if they're exactly the same?

like image 339
FanaHOVA Avatar asked Dec 14 '22 23:12

FanaHOVA


1 Answers

The comment from @arshajii explains why it is not a good idea to remove characters in the loop. To fix the issue in YOUR code, (Note that there are more efficient ways of achieving this, but it looks like you are learning, so I shall leave it here. )

def anti_vowel(text):
    vow = ["a", "e", "i", "o", "u"]
    chars = []

    for i in text: #No need of the two separate loops
        if i.lower() not in vow:
            chars.append(i)

    return "".join(chars)

Demo:

>>> def anti_vowel(text):
...     vow = ["a", "e", "i", "o", "u"]
...     chars = []
...     for i in text: #No need of the two separate loops
...         if i.lower() not in vow:
...             chars.append(i)
...     return "".join(chars)
... 
>>> anti_vowel("Hey look Words!")
'Hy lk Wrds!'
>>> anti_vowel("Frustration is real") 
'Frstrtn s rl'
>>> 
like image 126
karthikr Avatar answered Feb 06 '23 03:02

karthikr