TypeError: string indices must be integers

All other Source.Python topics and issues.
Xioto
Junior Member
Posts: 1
Joined: Sat Jun 19, 2021 4:46 pm

TypeError: string indices must be integers

Postby Xioto » Sat Jun 19, 2021 4:50 pm

So I have this bit of code that finds waveHeight and stores it as a cache, but when it reaches this section -

Code: Select all

sorted (data, key = lambda i: i['hours']) #sorts through cache_file data
print([0])
if 'waveHeight' in [0] and 'dwd' in [0]['waveHeight'] and[0]['waveHeight']['dwd'] >= 2.00: #if date and waveHeight found <2.00 then print
    print('Found')


It just gives me this error -

Code: Select all

    sorted (data, key = lambda i: i['hours']) #sorts through cache_file data
TypeError: string indices must be integers


I am in a bit of a hurry so if there is any more information you need then just ask, and I should respond soon!
User avatar
satoon101
Project Leader
Posts: 2697
Joined: Sat Jul 07, 2012 1:59 am

Re: TypeError: string indices must be integers

Postby satoon101 » Sat Jun 19, 2021 6:32 pm

The error indicates that data is not structured like you think it is. Print the value of data prior to the sorted line to verify it looks like you are intending it to.

*Edit: you might print type(data) as well to make sure the whole thing isn't a string.
Image
markfilan
Junior Member
Posts: 1
Joined: Mon Dec 06, 2021 5:59 am

Re: TypeError: string indices must be integers

Postby markfilan » Mon Dec 06, 2021 6:01 am

All the characters of a string have a unique index . This index specifies the position of each character of the string. TypeError: string indices must be integers means an attempt to access a location within a string using an index that is not an integer.

For example, str[hello"] and str[2.1] as indexes. As these are not integers, a TypeError exception is raised. This means that when you’re accessing an iterable object like a string or float value, you must do it using an integer value .

Python supports slice notation for any sequential data type like lists, strings , tuples, bytes, bytearrays, and ranges. When working with strings and slice notation, it can happen that a TypeError: string indices must be integers is raised, pointing out that the indices must be integers, even if they obviously are.

Return to “General Discussion”

Who is online

Users browsing this forum: No registered users and 17 guests