Search code examples
pythonstring

Changing lowercase characters to uppercase and vice-versa in Python


I'm trying to write a function which given a string returns another string that flips its lowercase characters to uppercase and viceversa.

My current aproach is as follows:

def swap_case(s):
    word = []
    for char in s:
        word.append(char)

    for char in word:
        if char.islower():
            char.upper()
        else:
            char.lower()

    str1 = ''.join(word)

However the string doesn't actually change, how should I alter the characters inside the loop to do so?

PS: I know s.swapcase() would easily solve this, but I want to alter the characters inside the string during a for loop.


Solution

  • def swap_case(s):
        swapped = []
    
        for char in s:
            if char.islower():
                swapped.append(char.upper())
            elif char.isupper():
                swapped.append(char.lower())
            else:
                swapped.append(char)
    
        return ''.join(swapped)