Home > OS >  'int' does not uspport indexing
'int' does not uspport indexing

Time:11-28

I am trying to make a loop for a string that contains 16 numbers, idea is to multiply *2 all the pair digits, but while doing that, I get an error of a string. I tried several ways but not succeeding.

cardNumber = input("Enter a 16-digit card number:")
cardNumber = int(cardNumber.replace(" ",""))
#cardNumber = str(cardNumber)
print(cardNumber)
i = 0
for i in range(0, 16, 2):
  cardNumber[i] *= 2
  print(cardNumber)

Can you help me to understand this simple issue? I do not understand why is not allowing it.

Thanks for the help

CodePudding user response:

You convert cardnumber to an integer, e.g. 4137894711755904. Integers do not have a "digit position", thus cardNumber[i] cannot work. This indexing works on strings, but not on number types.

You could convert the string to a list of integers, e.g.

card_number= input("Enter a 16-digit card number:")
digits = list(map(int, list(card_number.replace(" ","")))) 
# Line above is short for [int(i) for i in list(card_number.replace(" ",""))]

Now indexing works as exected. To get an integer back you can join the list and convert to int again, e.g.

number = int(''.join(map(str, digits)))

CodePudding user response:

the following maybe meet what you want :)

cardNumber = input("Enter a 16-digit card number:").replace(" ","")
numbers = [ int(x) for x in cardNumber ]
i = 0
for i in range(0, 16, 2):
  numbers[i] *= 2
  
print(numbers)

var = '' 
#iterate over the list elements
for element in numbers: 
    # converting integer to string and adding into variable
    var  = str(element)
 
# converting back into integer and printing the final result
print(int(var))
  • Related