[英]How can I find the sum of a string's indices in Python?
I am working on creating a program that has a function that takes in a string and prints the number of capital letters and also the sum of their indices.我正在创建一个程序,该程序具有一个函数,该函数接收一个字符串并打印大写字母的数量以及它们的索引总和。 like: "hEllo, World" 2 8
喜欢:“你好,世界”2 8
I have figured out the capital letters but I am having trouble with the indices.我已经弄清楚了大写字母,但我遇到了索引问题。
Here is what I have:这是我所拥有的:
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)
You can do this by first making a list of the upper-case character positions then getting the length and sum of that list, like this您可以通过首先制作一个大写字符位置列表然后获取该列表的长度和总和来做到这一点,就像这样
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"))
which returns返回
(2, 8)
If you want to print it on two lines, just get the tuple values and print them individually, like this:如果要将其打印在两行上,只需获取元组值并单独打印它们,如下所示:
c,s = count_upper("hEllo, World")
print(c)
print(s)
or if you want to format it, you can use something like this或者如果你想格式化它,你可以使用这样的东西
print("%d and %d" % (c,s))
print(f"{c} and {s}") # with python 3 f-strings
在导入 sys 和使用 sys.argv[1] 时,我们如何完成同样的程序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.