[Tutor] Messy - Very Messy string manipulation.
Alex Kleider
akleider at sonic.net
Wed Oct 28 12:54:46 EDT 2015
On 2015-10-28 08:09, Vusa Moyo wrote:
> Hi Guys,
>
> I've written a script to remove vowels from a string/sentence.
>
> the while loop I'm using below is to take care of duplicate vowels
> found in
> a sentence, ie
>
> anti_vowel('The cow moos louder than the frog')
>
> It works, but obviously its messy and n00by. Any suggestions on how I
> can
> write this code better?
>
>
> ----
> def anti_vowel(text):
> vowel = ['a', 'e', 'i', 'o', 'u']
> VOWEL = ['A', 'E', 'I', 'O', 'U']
> manip = []
>
> for i in text:
> manip.append(i)
> fufu = 0
> #
> while fufu < 16:
> for x in vowel:
> if x in manip:
> manip.remove(x)
>
> for y in VOWEL:
> if y in manip:
> manip.remove(y)
>
> fufu = fufu + 2
>
> strong = ''.join(manip)
> return strong
>
> ----
>
> Thanks - Vusa
This struck me as a good place to utilize list comprehension.
VOWELS = 'aeiouAEIOU'
def remove_chars(s, chars2remove=VOWELS):
"""Returns the string s but without any of
the characters found in chars2remove.
If given only one parameter, defaults to removing vowels.
"""
s_as_list = [char for char in s]
without_chars2remove = [
char for char in s_as_list if char not in chars2remove]
# print(s_as_list) # for testing
# print(without_chars2remove) # ditto
return "".join(without_chars2remove)
if __name__ == "__main__":
print(remove_chars(
'The cow moos louder than the frog'))
There may be some other constructs (the string join method on the empty
string)
to which you haven't yet been exposed.
Confession: I'm submitting it probably as much to garner comments from
the
pundits as to help you.
cheers,
Alex
More information about the Tutor
mailing list