1

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"))
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Sherafati
  • 196
  • 1
  • 10

2 Answers2

2

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?)

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • is it possible to apply changes to the 'a' parameter directly? without creating a new variable. like a = a.replace(a[chars], a[chars].upper()) – Sherafati Apr 12 '20 at 09:29
  • @Shera trying to "manipulate" a python string is bad - strings are immuteable - essentially you destroy the original string and create a new one over and over and over which is simply bad. So no, there is no way to mutate an _immuteable_ string in python. Using a list and joining it back is the way to go. See f.e. [changing-one-character-in-a-string-in-python](https://stackoverflow.com/questions/1228299/changing-one-character-in-a-string-in-python). `a = a.replace(a[chars], a[chars].upper())` does nothing to your original string, it assignes a new string to the same named variable – Patrick Artner Apr 12 '20 at 09:32
  • So this is what i understood, correct me if i'm wrong: let's say we have this string a = "AaAaA" and we want to replace only the a[1] element with "b", since a[1] is a lowercase "a" if we use a.replace(a[1], "b") function, it will replace every lowercase "a" with "b" in the entire string and not just the second element of the string and if we want to replace only the second element we'll have to use the code that you provided (and of course manipulate a[1] and add it to a NEW variable and leave the the others untouched.) correct? – Sherafati Apr 12 '20 at 09:51
  • You can use str.replace() and limit the amount of replacements BUT it will only ever replace the first one. (https://docs.python.org/3/library/stdtypes.html#str.replace on how to specify the count) It wont help you because you still change `AaAaAa` to `aaAaAa` (index 0 == a) then to `AaAaAa`(index 1 = a) then to `AaAaA` (index 2 = A) etc. because only ever change the first occurence of the character at the index you are at. My code goes ones through your string, takes one character at a time and places the opposit upper/lower into the list &at end returns string of the list – Patrick Artner Apr 12 '20 at 10:05
1

The problem was that you were doing a replace of all ocurrances of that character in the string. Here you have a working solution:

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

print(myFunc("AaAAaaaAAaAa"))
pcampana
  • 2,413
  • 2
  • 21
  • 39
  • So you create a new variable called 'result' and yes it works this way, but is it possible to apply the changes to the parameter 'a' using replace method as in the code i've provided? why does it not work. like: a= a.replace(a[chars], a[chars].upper()) – Sherafati Apr 12 '20 at 09:27
  • trying to "manipulate" a python string is bad - strings are immuteable - essentially you destroy the original string and create a new one over and over and over which is simply bad. If you append to `a` its the same, you create a new string and assign it to the same variable. So no, there is no way to mutate an _immuteable_ string in python. Using a list and joining it back is the way to go. See f.e. [changing-one-character-in-a-string-in-python](https://stackoverflow.com/questions/1228299/changing-one-character-in-a-string-in-python) – Patrick Artner Apr 12 '20 at 09:31