Justsoft
Justsoft

Reputation: 146

TypeError: string indices must be numbers, not object (Python)

I'm trying to create a long calculation calculator ( does long division, addition etc.) while in the long division section I'm trying to get the number to divide with but I can't (as in numdiv)

Ex: In 240 / 12, the number I'm trying to find is 24, then I'll have another loop that will add 12 to find 2 (as in 24/12 is 2).

Here is my code:

##############
#number is bigger (or equal) to number 2

number = 19000
operation = '/'
number2 = 12

##############

import math

longer = len(str(number))
shorter = len(str(number2))
if operation == '/':
    print str(number2) + '/' + str(number)
for i in range(longer - 1):
    if int(str(number)[0, i]) >= number2:
        numdiv = int(str(number)[0, i])
for i in range(1, math.trunc(numdiv / number2)):
    if number2 * (i + 1) >= numdiv:
        print (shorter + 1) * ' ' + number * i

The error is 5 lines from the end where I did

if int(str(number)[0, i]) >= number2:

It said

TypeError: string indices must be numbers, not object

NEW

I tried doing

if str(number)[:i] >= number2:
        numdiv = str(number)[:i]
for i in range(1, math.trunc(numdiv / number2)):
    if number2 * (i + 1) >= numdiv:
        print (shorter + 1) * ' ' + number * i

numdiv in this case is trying to be an integer and doing this causes the problem:

ValueError: invalid literal for int() with base 10: ''

How do I fix this?

Upvotes: 2

Views: 105

Answers (1)

timgeb
timgeb

Reputation: 78690

With somestring[0, i] you are trying to index into a string using a tuple.

Proof:

>>> class mystr(str):
...     def __getitem__(self, x):
...         print(x, type(x))
... 
>>> f = mystr('foo')
>>> f[0, 1]
((0, 1), <type 'tuple'>)

Trying to index into a string using anything but integers will give you a TypeError.

If you want a slice from your string up to position i, use

str(number)[0:i]

or just

str(number)[:i]

which does the same.

Upvotes: 0

Related Questions