如何计算字符串中写较少代码的大小写字母?

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

我一直在尝试计算大写字母和小写字母,然后通过比较它们,我试图根据某些条件以大写或小写形式打印字符串。在第一种方法中,我的代码可以运行并显示输出,但它看起来很乱,所以我尝试了第二种方法,使它看起来更短、更不笨拙。但是我的代码不起作用。


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

第二种方式:

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

如果大写字母个数多,这里只显示小写字母eve

和你的第一种方式一样,我用c>='A' and c<='Z'来判断号码。大小写

str1 = "HEY tHeRE Whats UP"

no_of_ucase, no_of_lcase = 0,0

for c in str1:
    if c>='A' and c<='Z':
        no_of_ucase += 1
    if c>='a' and c<='z':
        no_of_lcase += 1

print("Input string is: ", str1)
print("Total number of uppercase letters: ", no_of_ucase)
print("Total number of lowercase letters: ", no_of_lcase)

结果:

Input string is:  HEY tHeRE Whats UP
Total number of uppercase letters:  9
Total number of lowercase letters:  6

希望对您有所帮助

这样算怎么样?

upper_count = sum(c.isupper() for c in word)
lower_count = sum(c.islower() for c in word)
if upper_count > lower_count:
  print(word.upper())
else:
  print(word.lower())

@HiFile the best file manager 的回答是最简洁的,但这将解决为什么你的第二种方法不起作用。

你的第二种方法差不多可以用了。您只是没有将 count_up_and_low(word) 的输出分配给任何东西。您可以使用元组解包来解决这个问题(编辑后的行带有注释):

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

你应该这样做

str1 = "HEY tHeRE Whats UP"
lower_count = len([i for i in str1.replace(' ','') if i.islower()]) 
print(lower_count, '\t', len(str1.replace(' ','')) - lower_count)