简体   繁体   English

字符串索引必须是python中的整数错误,但索引是整数

[英]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. 我不断收到“字符串索引必须是整数”错误,但是当我在所有索引上调用type时,它们都显示为整数。

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] and S[a:len(S)] (slicing) rather than commas. 您可能打算使用S[0:a]S[a:len(S)] (切片)而不是逗号。

A note about slicing... 关于切片的说明...

You don't have to specify the leading zero or the trailing len(S) there - they're implicit. 您不必在此处指定前导零或结尾len(S) -它们是隐式的。 So you could just use S[:a] and S[a:] to mean the same thing. 因此,您可以只使用S[:a]S[a:]来表示同一件事。

Also note that S[0:a] + S[a:len(S)] is equivalent to S . 另请注意, S[0:a] + S[a:len(S)]等效于S You probably didn't want to include the + in there, so you'd probably want to use S[a+1:len(S)] instead. 您可能不想在其中包含+ ,因此您可能想使用S[a+1:len(S)]

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: 您不需要手动遍历索引-已经有字符串的.index()方法来执行此操作:

>>> "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: 您可以只使用split()函数来获取由+字符分隔的字符串部分:

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 . 作为奖励,这将适用于任意数量的数字1+2+3将起作用,就像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. 第四行利用Python的build in sum()函数,该函数将自动返回一系列项目的总和。

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. 我只是将其间隔开以便于解释。

0, a is a tuple. 0, a是一个元组。 Did you mean to slice the sequence instead, via S[0:a] ? 您是不是要通过S[0:a]对序列进行切片

您需要将修改为:

Sum = (S[0:a])+(S[a: len(S)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM