Changing from UPPERCASE to lowercase and vice versa for specific letters from an input (Python)

Question:

So I have to write this code where I should ask for input and validate for it to be a valid text. Then I have to change the register of every third element in the text (HeLlo -> Hello or HELLO -> HElLO).

I’ve done the first part where I have to prompt the user for input and validate it, but I can’t figure out how to change from uppercase/lowercase and vice versa for every third letter. I thought about trying to input the letters into an array and using .lower() .upper(). I also thought about inputting them into an array and using .swapcase(). And the second option seems more logical to me. However, I can’t seem to figure out how to exactly do it. Any help is greatly appreciated

while True:
    x = input("Please enter a text: ")
    if not x.isalpha():
        print("Please enter a valid text: ")
        continue
    else:
        print(x.swapcase())
    break
Asked By: Juj

||

Answers:

You can iterate through your word with enumerate and build a new string:

while True:
    x = input("Please enter a text: ")
    if not x.isalpha():
        print("Please enter a valid text: ")
        continue
    else:
        result = ""
        for i, letter in enumerate(x):
            if i % 3 == 2:
                result += letter.swapcase()
            else:
                result += letter
    break

print(result)
Answered By: jprebys
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.