Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String method doesn`t work in Function // Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Upper Letters count:  14
Lower Letters count:  18

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading