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))
The immediate issue
You probably meant to use
S[0:a]andS[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 useS[:a]andS[a:]to mean the same thing.Also note that
S[0:a] + S[a:len(S)]is equivalent toS. You probably didn’t want to include the+in there, so you’d probably want to useS[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: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:As a bonus, this will work for an arbitrary number of numbers –
1+2+3would work, as would just4.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:
This is a much tidier form; I just spaced it out above to make it easier to explain.