字符串中元音重复
我想要输入一个字符串,然后返回这个字符串,每个元音字母都要重复四次,最后加一个“!”在后面。比如说,输入'hello',应该返回'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!'。我还在交互式命令行中尝试过,把元音字母定义为('a', 'e', 'i', 'o', 'u'),但是用同样的代码却得到了这个结果:
>>> for a in s:
if a in vowels:
s.replace(a, a * 4) + '!'
'heeeello!' 'helloooo!'
我该怎么做才能让每个元音字母都重复,而不是只重复其中一个呢?
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!
这样做的好处是只需要扫描字符串一次。(而且在我看来,它的意思也比较容易理解)。
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 + '!'