Reputation: 25
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
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
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
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
text
, orvowels
to contain uppercase vowels: vowels = set('aeiouAEIOU')
, orUse 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
Reputation: 137398
Two problems:
strip
is the wrong method; it only removes from the beginning and end of a string. Use .replace(something, '')
.strip
returns the modified string.Upvotes: 1