Skip to content
Advertisement

How to uppercase even letter and lowercase odd letter in a string?

I am creating a function that takes in a string and returns a matching string where every even letter is uppercase and every odd letter is lowercase. The string only contains letters

I tried a for loop that loops through the length of the string with an if statement that checks if the index is even to return an upper letter of that index and if the index is odd to return a lowercase of that index.

def my_func(st):
    for index in range(len(st)):
        if index % 2 == 0:
            return st.upper()
        else:
            return st.lower()

I expected to have even letters capitalize and odd letter lowercase but I only get uppercase for the whole string.

Advertisement

Answer

Some issues in your code:

  • Currently you are returning from the function on the first index itself, i.e index=0 when you do return st.lower(), so the function will stop executing after it encounters the first index and breaks out of the for loop

  • Doing st.lower() or st.upper() ends up uppercasing/lowercasing the whole string, instead you want to uppercase/lowercase individual characters

One approach will be to loop over the string, collect all modified characters in a list, convert that list to a string via str.join and then return the result at the end

You also want to refer to each individual characters via the index.

def my_func(st):

    res = []
    #Iterate over the character
    for index in range(len(st)):
        if index % 2 == 0:
            #Refer to each character via index and append modified character to list
            res.append(st[index].upper())
        else:
            res.append(st[index].lower())

    #Join the list into a string and return
    return ''.join(res)

You can also iterate over the indexes and character simultaneously using enumerate

def my_func(st):

    res = []
    #Iterate over the characters
    for index, c in enumerate(st):
        if index % 2 == 0:
            #Refer to each character via index and append modified character to list
            res.append(c.upper())
        else:
            res.append(c.lower())

    #Join the list into a string and return
    return ''.join(res)
print(my_func('helloworld'))

The output will be

HeLlOwOrLd
Advertisement