我正在尝试将一个字符串作为输入并返回相同的字符串,每个元音乘以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) + '!'
Run Code Online (Sandbox Code Playgroud)
上面的代码只返回'heeeello!' 我也尝试在交互式shell中使用元音等于('a','e','i','o','u'),但使用相同的代码导致:
>>> for a in s:
if a in vowels:
s.replace(a, a * 4) + '!'
Run Code Online (Sandbox Code Playgroud)
'heeeello!' 'helloooo!'
我怎样才能使它成倍增加每个元音而不仅仅是其中一个元音?
我个人会在这里使用正则表达式:
import re
def f(text):
return re.sub(r'[aeiou]', lambda L: L.group() * 4, text, flags=re.I) + '!'
print f('hello')
# heeeelloooo!
Run Code Online (Sandbox Code Playgroud)
这具有仅扫描字符串一次的优点.(而且恕我直言,它正在做什么,这是相当可读的).
你是循环遍历字符串,如果字符是元音,你用字符串中的四个元素替换元音然后停止.这不是你想要做的.相反,循环元音并替换字符串中的元音,将结果分配回输入字符串.完成后,返回带有感叹号的结果字符串.
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 + '!'
Run Code Online (Sandbox Code Playgroud)