[英]Receive “TypeError: string indices must be integers” when iterating over one piece of code
I am taking an input with 我正在与
CC = (input("What is your credit card number?"))
When I take the sum of every other digit, starting from the first, I use this code (which works): 当我从第一位开始取所有其他数字的总和时,我使用以下代码(有效):
amex_sum = sum(int(i) for i in CC[::2])
However, when I try to take the sum of every other digit, starting from the second digit and until the 16th digit, with the following code 但是,当我尝试从第二个数字到第16个数字取其他两位数的总和时,请使用以下代码
MC_sum = sum(int(i) for i in CC[1,15,2])
I receive the error: "TypeError: string indices must be integers." 我收到错误:“ TypeError:字符串索引必须是整数。”
Why does one iteration work and not the other? 为什么一个迭代有效,而另一个无效? Isn't the code essentially the same? 代码本质上是不一样的吗?
You're slicing it incorrectly, you are doing CC[1,15,2]
but this creates a tuple (1, 15, 2)
to be indexed in CC
This wont work of course as CC is a string and takes only integer indices. 您将其切片不正确,您正在执行CC[1,15,2]
但这会创建一个元组(1, 15, 2)
CC[1,15,2]
(1, 15, 2)
,以在CC
索引。由于CC是字符串并且仅接受整数索引,因此这当然不会起作用。
What you want is CC[1:15:2]
to slice from the second index to the sixteenth with a step of two. 您想要的是CC[1:15:2]
以第二步从第二个索引切片到第16个索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.