iKyriaki
iKyriaki

Reputation: 609

Multiplying vowels in a string

I'm attempting to take a string as input and return that same string with each vowel multiplied by 4 and a "!" added at the end. Ex. 'hello' returns, 'heeeelloooo!'

def exclamation(s):
'string ==> string, returns the string with every vowel repeating four times and an exclamation mark at the end'
vowels = 'aeiouAEIOU'
res = ''
for a in s:
    if a in vowels:
        return s.replace(a, a * 4) + '!'

The above code just returns 'heeeello!' I also attempted it in the interactive shell with vowels equaling ('a', 'e', 'i', 'o', 'u') but using the same code resulted in this:

>>> for a in s:
if a in vowels:
    s.replace(a, a * 4) + '!'

'heeeello!' 'helloooo!'

How can I get it to multiply each vowel and not just one of them?

Upvotes: 0

Views: 1446

Answers (2)

icktoofay
icktoofay

Reputation: 129099

As is, you're looping over the string, and if the character is a vowel, you're replacing that vowel in the string with four of it and then stopping. That's not what you want to do. Instead, loop over the vowels and replace the vowel in the string, assigning the result back to the input string. When you're done, return the resulting string with an exclamation mark appended.

def exclamation(s):
    'string ==> string, returns the string with every vowel repeating four times and an exclamation mark at the end'
    vowels = 'aeiouAEIOU'
    for vowel in vowels:
        s = s.replace(vowel, vowel * 4)
    return s + '!'

Upvotes: 5

Jon Clements
Jon Clements

Reputation: 142216

I would personally use a regexp here:

import re

def f(text):
    return re.sub(r'[aeiou]', lambda L: L.group() * 4, text, flags=re.I) + '!'

print f('hello')
# heeeelloooo!

This has the advantage of scanning the string only once. (And IMHO is fairly readable as to what it's doing).

Upvotes: 8

Related Questions