如何保持元音大写在同一位置?

2024-09-30 20:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个函数来反转文本字符串中的元音。我发现如果我使用text[item].upper(),它会创建一个单独的空间来进行更改,但不会影响原始列表。你知道吗

像“Ello world”这样的字符串应该看起来像“Ollo werld”,但问题是我的函数将原始字符串返回为“Ollo werld”。你知道吗


Tags: 函数字符串text文本列表world空间item
3条回答
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)

您可以简单地用大写字母替换您的字母,如下所示:

text[x] = text[x].upper()

编辑:我不知道为什么会被否决,但是当您按照建议用.lower()和.upper()函数调用替换行时,您确实会得到预期的结果。你知道吗

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)

EDIT:此函数返回所需的结果,同时避免使用嵌套循环。你知道吗

相关问题 更多 >