Search code examples
pythonstringreplaceuppercaselowercase

Problem with changing lowercase letters to uppercase and vice versa using str.replace


Ok, so this is my code, i don't want to use the built in swapcase() method. It does not work for the given string.

def myFunc(a):
    for chars in range(0,len(a)):
        if a[chars].islower():
            a = a.replace(a[chars], a[chars].upper())
        elif a[chars].isupper():
            a = a.replace(a[chars], a[chars].lower())
    return a

print(myFunc("AaAAaaaAAaAa"))

Solution

  • replace changes all the letters and you assign the values back to aso you end up with all upper cases.

    def myFunc(a):
        # use a list to collect changed letters
        new_text = []
        for char in a:
            if char.islower():
                new_text.append(char.upper())
            else:
                new_text.append(char.lower())
    
        # join the letters back into a string
        return ''.join(new_text)
    
    print(myFunc("AaAAaaaAAaAa"))  # aAaaAAAaaAaA
    

    or shorter:

    def my2ndFunc(text):
        return ''.join( a.upper() if a.islower() else a.lower() for a in text)
    

    using a list comprehension and a ternary expression to modify the letter (see Does Python have a ternary conditional operator?)