简体   繁体   English

遍历一段代码时收到“ TypeError:字符串索引必须为整数”

[英]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.

相关问题 TypeError:字符串索引必须是迭代嵌套字典的整数 - TypeError: string indices must be integers from iterating through nested dictionaries 类型错误:字符串索引必须是整数 - TypeError:string indices must be integers TypeError:字符串索引必须是整数 - TypeError : string indices must be integers / string索引处的TypeError必须是整数 - TypeError at / string indices must be integers TypeError:字符串索引必须是整数 - TypeError: string indices must be integers 对于dict中的in循环给出TypeError:字符串索引必须为整数 - For in loop over dict gives TypeError: string indices must be integers Python for循环json数据仅在单个数据元素时抛出'TypeError:字符串索引必须为整数' - Python for loop over json data throws 'TypeError: string indices must be integers' only when a single element of data TypeError:遍历每一行以获得特定列值时,字符串索引必须是整数 - TypeError: string indices must be integers when iterrating over each row to get a specific column value 类型错误:使用带有字符串参数的 itemgetter 时,字符串索引必须是整数 - TypeError: string indices must be integers when using itemgetter with string argument TypeError:通过Python读取JSON时,字符串索引必须为整数 - TypeError: string indices must be integers when read JSON via Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM