2013-02-22 50 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

相關問題