正在解决一个家庭作业问题,要求我们创建一个函数,其中字符串中的所有元音都被反转。例如: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/