Reputation: 123
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
MC_sum = sum(int(i) for i in CC[1,15,2])
I receive the error: "TypeError: string indices must be integers."
Why does one iteration work and not the other? Isn't the code essentially the same?
Upvotes: 0
Views: 43
Reputation: 836
You're slicing it incorrectly, you are doingCC[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.
What you want is CC[1:15:2]
to slice from the second index to the sixteenth with a step of two.
Upvotes: 1