def reversevowel(text):
cap_indexes = [a for a, b in enumerate(text) if b.isupper()]
text = list(text.lower())
vowels = ('aeiouAEIOU')
x = 0
y = len(text) - 1
while x < y:
while (text[x] not in vowels and x < min(len(text) - 1, y)):
x += 1
while (text[y] not in vowels and y > max(0, x)):
y -= 1
text[x], text[y] = text[y], text[x]
x += 1
y -= 1
for n in cap_indexes:
text[n] = text[n].upper()
return ''.join(text)
def reversevowel(text):
vowels = 'aeiouAEIOU'
text_list = list(text)
char_position = []
char_uppercase = []
char_list = []
# Iterate through characters in text
for i, c in enumerate(text_list):
if c in vowels:
char_position.append(i) # Add vowel position to list
char_uppercase.append(c.isupper()) # Add uppercase boolean to list
char_list.insert(0, c) # Use as stack. Insert character
zipped_list = list(zip(char_position, char_list, char_uppercase))
for letter in zipped_list:
position, character, uppercase = letter
text_list[position] = str(character).upper() if uppercase else str(character).lower()
return ''.join(text_list)
您可以简单地用大写字母替换您的字母,如下所示:
编辑:我不知道为什么会被否决,但是当您按照建议用.lower()和.upper()函数调用替换行时,您确实会得到预期的结果。你知道吗
EDIT:此函数返回所需的结果,同时避免使用嵌套循环。你知道吗
相关问题 更多 >
编程相关推荐