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