python - 如何将颠倒的元音大写?

标签 python function for-loop

正在解决一个家庭作业问题,要求我们创建一个函数,其中字符串中的所有元音都被反转。例如:This Is So Fun 将返回 Thus Os Si Fin。只是不知道如何让该函数检测大写字母的位置并将其转换为小写字母,反之亦然。现在该函数输出 Thus os SI Fin

def f(word):
    vowels = "aeiouAEIOU"
    string = list(word)
    i = 0
    j = len(word)-1

    while i < j:
        if string[i].lower() not in vowels:
            i += 1
        elif string[j].lower() not in vowels:
            j -= 1
        else:
            string[i], string[j] = string[j], string[i]
            i += 1
            j -= 1

    return "".join(string)

最佳答案

如果您创建一个小函数,该函数需要两个字符并返回每个字符的大小写,您可以简单地将您的作业包装在其中:

def swapCase(c1, c2):
    return  (
        c1.upper() if c2.isupper() else c1.lower(), 
        c2.upper() if c1.isupper() else c2.lower()
    )


def f(word):
    vowels = "aeiouAEIOU"
    string = list(word)
    i = 0
    j = len(word)-1

    while i < j:
        if string[i].lower() not in vowels:
            i += 1
        elif string[j].lower() not in vowels:
            j -= 1
        else:
            string[i], string[j] = swapCase(string[j], string[i])
            i += 1
            j -= 1

    return "".join(string)

f("This Is So Fun")
# 'Thus Os Si Fin'

关于python - 如何将颠倒的元音大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59187325/

相关文章:

python - 我无法使用 pyodbc 从 MySQL 正确打印字符

javascript - 在对象内的函数之间传递值

javascript - 有没有一种方法可以在一个函数定义中提供两组剩余参数?

javascript - 为什么for循环没有运行?

c - 编写一个C程序,使用for循环从字符串中提取字符串的一部分

python - 提取和解析 pandas 数据框中的日期

python - 在 beautifulsoup 中提取 th 之后的链接

python - 替换非字母数字字符,除了一些异常(exception) python

r - 如何从函数内打印空行?

Java作业(使用for循环填充数组)