![](/img/trans.png)
[英]How can I find the indices of any two of the numbers, whose sum is equal to the target sum in Python?
[英]How can I find the sum of a string's indices in Python?
我正在創建一個程序,該程序具有一個函數,該函數接收一個字符串並打印大寫字母的數量以及它們的索引總和。 喜歡:“你好,世界”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)
您可以通過首先制作一個大寫字符位置列表然后獲取該列表的長度和總和來做到這一點,就像這樣
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
在導入 sys 和使用 sys.argv[1] 時,我們如何完成同樣的程序
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.