[python] TypeError: 'int' object is not subscriptable

I'm trying to create a simple program that tells you your lucky number according to numerology. I keep on getting this error:

File "number.py", line 12, in <module>
    sumln = (int(sumall[0])+int(sumall[1]))
TypeError: 'int' object is not subscriptable

My script is:

birthday = raw_input("When is your birthday(mm/dd/yyyy)? ")
summ = (int(birthday[0])+int(birthday[1]))
sumd = (int(birthday[3])+int(birthday[4]))
sumy= (int(birthday[6])+int(birthday[7])+int(birthday[8])+int(birthday[9]))
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumln = (int(sumall[0])+int(sumall[1]))
print "Your lucky number is", sumln`   

This question is related to python python-2.7

The answer is


sumall = summ + sumd + sumy

Your sumall is an integer. If you want the individual characters from it, convert it to a string first.


You can't do something like that: (int(sumall[0])+int(sumall[1]))

That's because sumall is an int and not a list or dict.

So, summ + sumd will be you're lucky number


The error is exactly what it says it is; you're trying to take sumall[0] when sumall is an int and that doesn't make any sense. What do you believe sumall should be?


Just to be clear, all the answers so far are correct, but the reasoning behind them is not explained very well.

The sumall variable is not yet a string. Parentheticals will not convert to a string (e.g. summ = (int(birthday[0])+int(birthday[1])) still returns an integer. It looks like you most likely intended to type str((int(sumall[0])+int(sumall[1]))), but forgot to. The reason the str() function fixes everything is because it converts anything in it compatible to a string.


Try this instead:

sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumall = str(sumall) # add this line
sumln = (int(sumall[0])+int(sumall[1]))
print "Your lucky number is", sumln

sumall is a number, and you can't access its digits using the subscript notation (sumall[0], sumall[1]). For that to work, you'll need to transform it back to a string.