2013-02-22 53 views
0

我试图把一个字符串作为输入,并返回相同的字符串,每个元音乘以4并加上一个“!”最后添加。防爆。 '你好'返回,'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) + '!' 

上面的代码只是返回'heeeello!'我也尝试过与元音等于交互shell( 'A', 'E', 'I', 'O', 'U'),但使用相同的代码导致了这一点:

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

“heeeello ! 'helloooo!'

我怎样才能让它乘以每个元音而不只是其中的一个?

回答

5

现在,您正在循环查看字符串,如果字符是元音,则用四个元素替换字符串中的元音,然后停止。这不是你想要做的。相反,循环元音并替换字符串中的元音,将结果分配回输入字符串。完成后,返回带有感叹号的结果字符串。

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 + '!' 
+0

谢谢!我现在看到我做错了什么。完美的作品。 – iKyriaki 2013-02-22 02:44:46

8

我会亲自使用正规的位置:

import re 

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

print f('hello') 
# heeeelloooo! 

这有扫描线只有一次的优势。 (和恕我直言是相当可读的,它在做什么)。

+1

我对python还是比较新的,所以对我来说这是相当先进的。它确实有效,但我现在还不太了解(也许将来我会这样做)。非常感谢你的帮助! – iKyriaki 2013-02-22 02:45:04

+2

项目'r'[aeiou]''表示任何元音,'lambda'表达意味着采用与正则表达式匹配的任何元素,并将其替换为该字符串的4倍。最后,标志're.I'告诉正则表达式忽略该情况(所以'A''也会匹配)。 – 2013-02-22 02:47:45

+0

哦,我明白了。这并在文档中查看它使其更有意义。那么“lambda L:L.group()”中的L是否有任何意义或者它只是一个变量? – iKyriaki 2013-02-22 02:57:07

相关问题