【问题标题】:How can I find the sum of a string's indices in Python?如何在 Python 中找到字符串索引的总和?
【发布时间】:2022-07-22 10:07:00
【问题描述】:

我正在创建一个程序,该程序具有一个函数,该函数接收一个字符串并打印大写字母的数量以及它们的索引总和。 喜欢: “你好世界” 2 8

我已经找到了大写字母,但我在索引方面遇到了问题。

这是我所拥有的:

import sys

def Count(str):

str = sys.argv[1]

upper, lower, number, special = 0,0,0,0

for i in range(len(str)):
    if str[i].isupper():
        upper += 1
    elif str[i].islower():
        lower += 1
    elif str[i].isdigit():
        number +=1
    else:
        special += 1
        
        
print(upper)
print(lower)


Count(str)

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以先制作一个大写字符位置列表,然后获取该列表的长度和总和,如下所示

    def count_upper(inp_str):
        # Get a list of the indices of the upper-case characters,
        # enumerate returns a list of index,character pairs, then you
        # keep only the indices with an upper case character
        uppers = [i for i,s in enumerate(inp_str) if s.isupper()]
    
        # number of upper-case chars is the length of the list of indices
        num_uppers = len(uppers)
    
        # index sum is straightforward
        sum_indices = sum(uppers)
    
        return num_uppers, sum_indices
        
    print(count_upper("hEllo, World"))
    

    返回

    (2, 8)
    

    如果要分两行打印,只需获取元组值并单独打印,如下所示:

    c,s = count_upper("hEllo, World")
    print(c)
    print(s)
    

    或者如果你想格式化它,你可以使用类似这样的东西

    print("%d and %d" % (c,s))
    print(f"{c} and {s}") # with python 3 f-strings
    

    【讨论】:

    • 谢谢!你知道我怎么能在两行输出:2
    • 2 8 你知道我怎么能有这种格式的吗?我想也许 \n 但这没有用。谢谢@Tyler V!
    • 函数返回一个元组(两个值)。您可以获取它们并根据需要打印它们。我在答案中添加了一个示例。
    【解决方案2】:

    我们如何在导入 sys 和使用 sys.argv[1] 时完成同样的程序

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-14
      • 2012-05-26
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      相关资源
      最近更新 更多