'String method doesn`t work in Function // Python [duplicate]

I've created this function to trim spaces in between words in string to run over them and get upper and lower case letters count. The trouble is that "replace" method doesn't change the string and all spaces are counted as lowercase letters. I couldn't figure out why, so I wrote If statement to pass every time if i == " " ( which I actually didn't like), Is there any idea what I've done wrong?

My code:

testString = "Upper and Lower Case CALCULATION"

def case_counter(string, upperCount = 0, lowerCount = 0):
    for i in string:
        string.replace(" ", "")
        if i.isupper():
            upperCount += 1
        else:
            lowerCount += 1

    print("Upper Letters count: ", upperCount)
    print("Lower Letters count: ", lowerCount)

case_counter(testString)
print("\n")

My output:

Upper Letters count:  14
Lower Letters count:  18


Solution 1:[1]

You need to store the replace function return value in the same or diff variable.

testString = "Upper and Lower Case CALCULATION"

def case_counter(string, upperCount = 0, lowerCount = 0):
    string = string.replace(" ","") # Modified
    for i in string:
        if i.isupper():
            upperCount += 1
        else:
            lowerCount += 1

    print("Upper Letters count: ", upperCount)
    print("Lower Letters count: ", lowerCount)

case_counter(testString)
print("\n")

Also, I would like to suggest the best approach for this.

def case_counter(string):
   string = string.replace(" ","")
   upper_count = sum(i.isupper() for i in string)
   lower_count = len(string) - upper_count
   
   print("Upper Letters count: ", upper_count)
   print("Lower Letters count: ", lower_count)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1