-1

I have this code that seems to work just fine except that it's leaving out an "e"! The code is designed to loop through a given string, remove the vowels, then return the new anti-vowel string.

def anti_vowel(text):
    anti_v = ''
    for c in text:
        if c in "aeiouAEIOU":
            anti_v = text.replace(c, '')
        else:
            anti_v.join(c)
    return anti_v

Test code:

anti_vowel("Hey look Words!")

This returns "Hey lk Wrds!"

What gives? Thanks!

wahoowa
  • 45
  • 8
  • 1
    `anti_v.join(c)` doesn't do anything like what you're thinking it does. `text.replace(c, '')` also doesn't replace a specific instance of `'e'` or `'o'` or whatever; it replaces all instances. You're also throwing away the old replacements every time you perform another replacement. – user2357112 Jan 06 '17 at 00:03

3 Answers3

1

You could use a comprehension to join all the characters in your string that aren't vowels:

def anti_vowel(text):
    return ''.join(c for c in text if c not in 'aeiouAEIOU')
VHarisop
  • 2,816
  • 1
  • 14
  • 28
1

I think the problem is that you are storing the value in anti_v but each time you run through the loop, you are replacing the value of anti_v with the value of text.replace(c, ''), but the text variable does not change. So for example if text is 'aae'.

c = 'a' ---> anti_v = 'aae'.replace('a', '') --> anti_v='e'
c = 'a' ---> anti_v = 'aae'.replace('a', '') --> anti_v='e'
c = 'e' ---> anti_v = 'aae'.replace('e', '') --> anti_v='aa'

So the return of anti_vowel in this case would be 'aa' instead of an empty string.

One way to solve this problem is doing what @VHarisop suggested.

Also you can take a look on this thread to see other options to remove vowels on a string.

nicolastrres
  • 431
  • 6
  • 9
0

Each time you run through the loop you do a replace on the text parameter. But when you do a replace the original value doesn't change. So the next time you replace you are doing so on the original string. For example:

print(text.replace('e', '')) # Hy hy look txt!
print(text) # Hey hey look text!

It appears to work for the other vowels because your else joins c to anti_v.

You don't need the else at all though. Just set anti_v equal to text and do the replace on anti_v. That will solve your problem.

def anti_vowel(text):
    anti_v = text
    for c in text:
        if c in "aeiouAEIOU":
            anti_v = anti_v.replace(c, '')

    return anti_v

Or just remove the anti_v variable all together and use text:

def anti_vowel(text):
    for c in text:
        if c in "aeiouAEIOU":
            text = text.replace(c, '')

    return text
Andrew Hewitt
  • 518
  • 4
  • 14