Swapping uppercase and lowercase in a string

Marco G. de Pinto picture Marco G. de Pinto · Mar 27, 2016 · Viewed 23.8k times · Source

I would like to change the chars of a string from lowercase to uppercase.

My code is below, the output I get with my code is a; could you please tell me where I am wrong and explain why? Thanks in advance

test = "AltERNating"

def to_alternating_case(string):
    words = list(string)
    for word in words:
        if word.isupper() == True:
            return word.lower()
        else:
            return word.upper()  

print to_alternating_case(test)

Answer

folkol picture folkol · Mar 27, 2016

If you want to invert the case of that string, try this:

>>> 'AltERNating'.swapcase()
'aLTernATING'