编写一个Python函数,接受一个字符串并计算大写字母和小写字母的个数

新手上路,请多包涵

问题:编写一个 Python 函数,它接受一个字符串并计算大写字母和小写字母的个数。示例字符串:“你好罗杰斯先生,星期二你好吗?”预期输出:大写字符数:4 小写字符数:33

功能:

 def up_low(s):
  for a in s:
    u = u.count(a.isupper())
    l = l.count(a.islowwer())
  print(u, l)

为什么这个不起作用?

原文由 a81884855 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 596
2 个回答

您可以使用 List comprehensions 和 sum 函数来获取大小写字母的总数。

 def up_low(s):
    u = sum(1 for i in s if i.isupper())
    l = sum(1 for i in s if i.islower())
    print( "No. of Upper case characters : %s,No. of Lower case characters : %s" % (u,l))

up_low("Hello Mr. Rogers, how are you this fine Tuesday?")

输出:大写字符的数量:4,No。小写字符数:33

原文由 Bharath M Shetty 发布,翻译遵循 CC BY-SA 3.0 许可协议

你理解错了计数函数,计数,首先,是一个字符串函数,作为参数接受一个字符串,而不是这样做,你可以简单地做:

 def up_low(string):
  uppers = 0
  lowers = 0
  for char in string:
    if char.islower():
      lowers += 1
    elif char.isupper():
      uppers +=1
    else: #I added an extra case for the rest of the chars that aren't lower non upper
      pass
  return(uppers, lowers)

print(up_low('Hello Mr. Rogers, how are you this fine Tuesday?'))

4 33

原文由 developer_hatch 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题