Python Forum
TypeError: string indices must be integers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TypeError: string indices must be integers
#1
Error:
TypeError: string indices must be integers
What does this error mean?

I thought I would've fixed... by adding this
int(numbers[color])
in
while count <= 11:
        for color, value in band_values.items():
                if band_values[color] == int(numbers[color]):
                    return numbers
but didn't work & brought up the same error Cry

I'm new to using a dictionary. I'm trying to use one to help me convert the band values to numeric values by searching through a list.

#The first parameter is the two character string return earlier (numbers)
#This function will convert the two characters to a number value &
#return it.
def calculate_raw_value(numbers):

    count = 0

    band_values = {'K':'0', 'N':'1', 'R':'2', 'O':3'', 'Y':4,'G':5,
                   'L':6,'V':7, 'Z':8, 'W':9,
                   }
    

    while count <= 11:
        for color, value in band_values.items():
                if band_values[color] == numbers[color]:
                    return numbers

                elif count <= 9:
                    count = count + 1
                    continue

                elif count == 10:
                    print("ERROR")

Any extra advice/tips would be appreciated.
Reply
#2
First of all, on line 8, '1' is not a number. '1' is a string because of the quotes. 1 (without quotes) is a number.

For the rest of it, it's not clear because we don't see how you call the function, so we can't see what numbers is. But if you are looping over band_values.items(), color is going to be a key from band_values, and value is going to be the value associated with that key. Since all of your keys are strings, color is always going to be a string. int is not going to help you here, because int('K') is going to throw an error too ('K' being one of the possible keys).

Now if you fix the problem I mentioned on line 8, then all of your values should be integers, and you probably want numbers[value] instead of numbers[color]. Also note that on line 15, band_values[color] is equal to value, so you might as well just use that. But then I'm not sure why you are checking value == numbers[value]. Maybe you want numbers[count]? Again, it's not clear what is supposed to be happening here, so I'm not sure what the right answer is.

Finally, your while loop is going to go on forever. You only increase count if it is 9 or less, so count will always be 10 or less, and the condition of the while loop will always be True. Again, lack of clarity prevents me from knowing what a good fix would be.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Just seen this reply...
This is the whole program

#The parameter is a resistor sequence. Example NKOD.
#Returns TRUE if the length is equal to four & FALSE if its not.
#Define sequence as string
def check_length(sequence):
    """ (str) -> bool

    Return whether the length of the resistor sequence is valid.

    >>> check_length('NKOD')
    True
    >>> check_length('NKO')
    False
    """

    
    if len(sequence) == 4:
        return True
    else:
        return False



#The parameter is a resistor sequence with a valid length.
#Returns TRUE only if sequence contains uppercase G,K,L,N,O,R,V,W,Y,Z
#Anything else, such as lowercase will return FALSE
def check_colours(sequence, valid_colours ="DKLNORWYZ"):
    """ (str) -> bool

    Return True if and only if the sequence contains the letters G,K,L,N,O,R,V,W,Y,Z.

    >>> check_colours('NKOD')
    True
    >>> check_colours('NKOF')
    False
    """

    return all(color in valid_colours for color in sequence)    



#The parameter is a valid resistor sequence.
#Strip off the last 2 characters and returns the number portion as a string
def get_numbers(sequence):
    """ (str) -> str

    Return the numbers part of the sequence as a string.

    >>> get_numbers('NKOD')
    NK
    >>>get_numbers ('RRKS')
    RR
    """

    return numbers

#The parameter is the resistor sequence.
#Return True if and only if the multipler (2nd last character)
#conists of a DGKLNORSVY
def is_valid_multiplier(sequence, valid_multi ="DGKLNORSVY"):

    return all(multi in valid_multi for multi in multiplier)

#The parmeter is the resistor sequence.
#Return TRUE if and only if the tolerance (last character)
#consists of a DGLNRSVZ.
def is_valid_tolerance(sequence, valid_tolerance="DGLNRSVZ"):
    
    return all(tole in valid_tolerance for tole in tolerance)

#The first parameter is the two character string return earlier (numbers)
#This function will convert the two characters to a number value &
#return it.
def calculate_raw_value(numbers):

    count = 0

    band_values = {'K':0, 'N':1, 'R':2, 'O':3, 'Y':4,'G':5,
                   'L':6,'V':7, 'Z':8, 'W':9,
                   }
    

    while count <= 11:

        for color, value in band_values.items():

                if band_values[color] == numbers[value]:
                    return numbers

                elif count <= 9:
                    count = count + 1
                    continue

                elif count == 10:
                    print("ERROR")
        
    
    
#Program
sequence = str(input("Enter the resistor sequence: "))
numbers = sequence[:2]
multiplier = sequence[2]
tolerance = sequence[3]

#Test harness for testing purposes - will delete
print(check_length(sequence))
print(check_colours(sequence))
print(get_numbers(sequence))
print(is_valid_multiplier(sequence))
print(is_valid_tolerance(sequence))
calculate_raw_value(numbers)
I hope this gives you more clarity
Reply
#4
(Sep-29-2019, 04:51 PM)thecoziest Wrote: I hope this gives you more clarity

Well, it's more clear what the error is, but not really more clear what you are trying to do.

You've fixed the integers in band_values, but line 86 is a problem:

if band_values[color] == numbers[value]:
band_values[color] is an integer. But numbers is a string like 'NK' or 'RR' (based on lines 99-100). So indexing numbers gives you one character. But when is an integer going to be equal to 'N'? Never. Furthermore, numbers is necessarily a two character string (line 100 again). But the values in band_values go up to 9. As soon as you try to get numbers[9] you will get an index error.

Your while loop is still going to be an infinite loop, because count never gets past 10, much less 11. And I totally do not get what you are trying to do with the loop. Let's walk through it. Say your numbers are 'RR'. We start the while loop, and then start the for loop. In older versions we can't be sure, but newer Python versions should set color to 'K' and value to 0. So we check band_values['K'] against numbers[0]. Note that band_values['K'] is necessarily equal to value, because you are looping over items. band_values['K'] == numbers[0] is the same as 0 == 'R', obviously false. Since count is 1 (and thus <= 9), we add one to it and continue back to the next cycle of the for loop. Now color = 'N' and value = 1, so we check 1 against 'R' (the second 'R' in numbers). Again false, again we increase count to 2. The next time through the loop we have color = 'R' and value = 2. But that causes an error trying to get numbers[2].

Is that anything like what you are trying to do?
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: string indices must be integers, not str hanieh 4 98,313 Jan-04-2021, 05:13 AM
Last Post: delonbest
  please Help. TypeError: list indices must be integers, not str skamaaa01 1 4,351 Feb-04-2018, 12:33 PM
Last Post: Gribouillis
  create a 20 digit string, and cast to a list then add all the digits as integers nikhilkumar 2 6,320 Jul-19-2017, 04:53 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020