Python Dude
Python Dude

Reputation: 1

String Indices Must be Integers in Python

I am using Python to solve a contest problem. I am getting this error. I am fairly new and inexperienced with Python.

    for kek in sorteddic:
        lengthitem = int(len(kek))
        questionstring = start[0, lengthitem]

kek is essentially the "item" in "sorteddic" which is an array of strings.

The error I am getting is:

questionstring = start[0, lengthitem]
TypeError: string indices must be integers

Can someone please help? Thanks.

Upvotes: 0

Views: 2411

Answers (2)

paxdiablo
paxdiablo

Reputation: 881293

It's because the item you're trying to use as an index, 0, lengthitem, is not an integer but a tuple of integers, as shown below:

>>> x = 1 : type(x)
<class 'int'>
>>> x = 1,2 : type(x)
<class 'tuple'>

If your intent is to get a slice of the array (not entirely clear but I'd warrant it's a fairly safe guess), the correct operator to use is :, as in:

questionstring = start[0:lengthitem]

or, since 0 is the default start point:

questionstring = start[:lengthitem]

The following transcript shows how your current snippet fails and the correct way to do it:

>>> print("ABCDE"[1])
B

>>> print("ABCDE"[1,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

>>> print("ABCDE"[1:3])
BC

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95908

Slice notation uses colons, not commas (unless you are in numpy where commas separate dimensions in slices, athough under the hood that is treated as a tuple of slice objects). So use:

questionstring = start[0:lengthitem]

Upvotes: 0

Related Questions