1

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
Jan Wilamowski
  • 3,308
  • 2
  • 10
  • 23
llRub3Nll
  • 53
  • 1
  • 10
  • 5
    Strings cannot be changed. `string.replace` returns the new string. You need `string = string.replace(' ', '')` BEFORE the loop starts. – Tim Roberts May 11 '22 at 06:44
  • 1
    Strings are immutable in python. Replace returns a copy of modified string with characters replaced. See [str.replace](https://docs.python.org/3/library/stdtypes.html#str.replace) – Lesiak May 11 '22 at 06:44
  • Also, you shouldn't define your internal variables in the parameter list. Just initialize them in the function. – Tim Roberts May 11 '22 at 06:46
  • 1
    Bear in mind that space is neither upper nor lower. Therefore the idea that you need to remove (replace) them is irrelevant – DarkKnight May 11 '22 at 06:52

1 Answers1

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)
Nanthakumar J J
  • 860
  • 1
  • 7
  • 22