Search code examples
pythonstringindices

string indices must be integers error in python, but indices are integers


I'm writing a program to add two numbers from a single line of input of the form:

number + othernumber

I keep getting a "string indices must be integers" error, but when I call type on all the indices, they all show up as integers.

How do I fix this? Here's the code

S = input()
for position in range(0, len(S)):
   if '+'== position:
     break
a=int(position)
Sum = (S[0,a])+(S[a, len(S)])
print(Sum)
#print(position)   
#print(type(position))
#print(type(len(S)))
#print(type(0)) 

Solution

  • The immediate issue

    You probably meant to use S[0:a] and S[a:len(S)] (slicing) rather than commas.

    A note about slicing...

    You don't have to specify the leading zero or the trailing len(S) there - they're implicit. So you could just use S[:a] and S[a:] to mean the same thing.

    Also note that S[0:a] + S[a:len(S)] is equivalent to S. You probably didn't want to include the + in there, so you'd probably want to use S[a+1:len(S)] instead.

    Another note about finding the position of a character in a string

    You don't need to loop over the indices manually - there's already the .index() method of strings to do this:

    >>> "hello".index("e")
    1
    

    A simpler way to accomplish your overall goal

    You can just use the split() function to get the parts of a string separated by the + character:

    S = input()
    number_strings = S.split('+')
    numbers = [int(n) for n in number_strings]
    print sum(numbers)
    

    As a bonus, this will work for an arbitrary number of numbers - 1+2+3 would work, as would just 4.

    The third line uses what's called a list comprehension to operate on each of the elements of a list and generate a new one - in this case, taking a list of strings and making a list of integers.

    The fourth line takes advantage of Python's build in sum() function, which will automatically return the sum of a sequence of items.

    Note that you could also condense the above lines:

    print sum(int(n) for n in input().split('+'))
    

    This is a much tidier form; I just spaced it out above to make it easier to explain.