345. Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1: Given s = "hello", return "holle".

Example 2: Given s = "leetcode", return "leotcede".

亮瞎宝宝双眼的答案,必须广为宣传,【摘自https://leetcode.com/discuss/99073/1-2-lines-python-ruby】:

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = re.findall('(?i)[aeiou]', s)
        return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)

使用正则表达式 找出所有的元音字母

eg: s='hello'  则vowels = ['e', 'o']

re.sub的函数原型为:re.sub(pattern, repl, string, count)

其中第二个函数是替换后的字符串;

第四个参数指替换个数。默认为0,表示每个匹配项都替换

posted @ 2016-04-24 20:25  python挖掘  阅读(311)  评论(0编辑  收藏  举报