STNDR
STNDR

Reputation: 25

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

Upvotes: 2

Views: 905

Answers (4)

jpp
jpp

Reputation: 164663

str.strip is not an in-place operation and takes a string as an argument. Therefore, your code will not work as desired.

You can use bytearray to efficiently remove certain characters from your string. You may see an order of magnitude better performance for larger strings.

Character removal can be performed with bytearray.translate directly, without the need to use str.maketrans.

def anti_vowel_bytes(s):
    b = bytearray()
    b.extend(s.encode())
    b = b.translate(None, b'aeiou')
    return b.decode('utf-8') 

def anti_vowel_str(s, mapping):
    return s.translate(mapping)

vowels = set('aeiou')
mapping = str.maketrans(dict.fromkeys(vowels, ''))

test = 'alpha beta gamma delta epsilon zeta eta'*100000
res1 = anti_vowel_bytes(test)
res2 = anti_vowel_str(test, mapping)

assert res1 == res2

%timeit anti_vowel_bytes(test)            # 20 ms
%timeit anti_vowel_str(test, mapping)     # 398 ms

Upvotes: 0

STNDR
STNDR

Reputation: 25

This code worked too! The dude who wrote the anwser deleted their post. Shame it worked really well.

liz = ("Totally not going to hitting the big bong at the event")
import re

def anti_vowel(text):
    print re.sub('[aeiou]', '', text)

anti_vowel(liz)

output: 
Ttlly nt gng t httng th bg bng t th vnt

Upvotes: 0

cs95
cs95

Reputation: 402473

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))

Upvotes: 8

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

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.

Upvotes: 1

Related Questions