Str.replace Issue
I'm trying to get the following code working, it should remove vowels from a user-inputted string of text. def isVowel(text): if text in ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I'
Solution 1:
if (isVowel == True):
should be
ifisVowel(char):
isVowel
is a function object. isVowel == True
will always be False.
Note that you could also do this, faster and more simply with str.translate.
In [90]: 'Abracadabra'.translate(None, 'aeiouAEIOU')
Out[90]: 'brcdbr'
or, (as EOL points out) using regex:
In [93]: import re
In [95]: re.sub(r'(?i)[aeiou]', '', 'Abracadabra')
Out[95]: 'brcdbr'
However, str.translate
is faster in this case:
In [94]: %timeit 'Abracadabra'.translate(None, 'aeiouAEIOU')
1000000 loops, best of 3: 316 ns per loop
In [96]: %timeit re.sub(r'(?i)[aeiou]', '', 'Abracadabra')
100000 loops, best of 3: 2.26 us per loop
Solution 2:
You can do this in one line, because Python is awesome:
def withoutVowels(text):
return"".join(c for c intextif c notin"aeiouAEIOU")
Post a Comment for "Str.replace Issue"