user11319914
user11319914

Reputation:

How do I keep the capitalization of a vowel in same position?

I need a function that will reverse the vowels in a text string. I found out that if I use text[item].upper(), it creates a separate space where the change is made but it does not affect the original list.

A string like 'Ello world' should look like 'Ollo werld' but the issue is that my function returns the original string as 'ollo wErld'.

Upvotes: 3

Views: 98

Answers (3)

Kacper Dębowski
Kacper Dębowski

Reputation: 158

You can simply replace your letter with capitalized version like this:

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

When you replace lines with .lower() and .upper() functions calls as suggested, you do get the result expected.

Upvotes: 4

Mo'ops
Mo'ops

Reputation: 11

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)

Upvotes: 1

agdelig
agdelig

Reputation: 31

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: This function returns the required result while avoiding the use of nested loops.

Upvotes: -1

Related Questions