0

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?

4

2 回答 2

8

我个人会在这里使用正则表达式:

import re

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

print f('hello')
# heeeelloooo!

这样做的好处是只扫描字符串一次。(恕我直言,它在做什么是相当易读的)。

于 2013-02-22T02:37:23.630 回答
5

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 + '!'
于 2013-02-22T02:35:59.173 回答