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

How to count the uppercase and lowercase letters in string writing lesser code?

I have been trying to count the uppercase and lowercase letters, then by comparing them, I’m trying to print the string either in uppercase or lowercase based on some conditions. In the first method my code worked and output showed but it looks messy, so I tried the 2nd way to make it look shorter and less clumsy. But my code is not working.


str1="HEY tHeRE Whats UP"
upper1,lower1=0,0
for i in range(len(str1)):
  if str1[i].isupper():
    upper1+=1
  if str1[i].islower():
    lower1+=1
if upper1>lower1:
  print(str1.upper())
else:
  print(str1.lower())

2nd way:

def count_up_and_low(word):
  u = [x for x in word if x.isupper()]
  l = [x for x in word if x.islower()]
  return len(u),len(l) 
word="HEY THERE WHATS up"
count_up_and_low(word)
if u>l:
  print(word.upper())
else:
  print(word.lower())

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

>Solution :

The answer by @HiFile the best file manager is the most succinct, but this will address why your second method doesn’t work.

Your second method almost works. You are just not assigning the output of count_up_and_low(word) to anything. You can use tuple unpacking to fix this (edited line shown with comment):

def count_up_and_low(word):
    u = [x for x in word if x.isupper()]
    l = [x for x in word if x.islower()]
    return len(u),len(l) 

word="HEY THERE WHATS up"
u, l = count_up_and_low(word) # only edited this line
if u>l:
  print(word.upper())
else:
  print(word.lower())
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