Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing vowels from a string

I'm suppose remove all the vowels from the any string that would be entered. I'm trying to make the code as simple as possible.

Thank you for the help.

def anti_vowel(text):
    for i in text:
       i.strip(['i','o','a','u','e'])
       return i
like image 835
STNDR Avatar asked Dec 21 '25 17:12

STNDR


2 Answers

So you call strip on each character.... and then what? You don't update the string, because strings are immutable and i.strip is not an inplace operation.

A naive improvement over your solution would filtering characters out inside a list comprehension and then doing a join on the result:

vowels = {'i','o','a','u','e'}
def anti_vowel(text):
    return ''.join([c for c in text if c not in vowels])

A small note: if your string contains mixed case, you may want to either

  1. Lowercase text, or
  2. Augment vowels to contain uppercase vowels: vowels = set('aeiouAEIOU'), or
  3. Use str.casefold (as per @Adam Smith's comment)—augmenting vowels is no longer needed in that case:

    return ''.join([c for c in text if c.casefold() not in vowels])
    

You can get even better with str.translate (this works on python-3.x):

mapping = str.maketrans(dict.fromkeys(vowels, '')) # create a global mapping once
def anti_vowel(text):
    return text.translate(mapping))
like image 79
cs95 Avatar answered Dec 23 '25 05:12

cs95


Two problems:

  1. strip is the wrong method; it only removes from the beginning and end of a string. Use .replace(something, '').
  2. Strings are immutable; a method cannot modify a string. strip returns the modified string.
like image 43
Jonathon Reinhart Avatar answered Dec 23 '25 06:12

Jonathon Reinhart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!