Home > OS >  Python Condition : String indices must be integers
Python Condition : String indices must be integers

Time:09-06

enter image description here

I am trying to count the number of 'C's in each item in the list bins

The ideal output would be c_counter = [1, 1, 1, 0]

However when setting the condition if item[i] == "C", I kept getting the error string indices must be integers

I tried converting it to int using int(item[i]) but that didn't work too...

Any help would be greatly appreciated, thank you.

CodePudding user response:

When you iterate over a string with a for loop, you in fact iterate over its characters, not indexes in the string. I.e.:

for item in bins:
    for ch in item:
        if ch == 'C':
            c_counter  = 1

CodePudding user response:

you cause 'count' function :

bins=['ABCDE','ABCDE','GHCGA','B']
c_counter=[]
for i in bins:
  c_counter.append(i.count('C'))

c_counter

enter image description here

CodePudding user response:

Try this List Comprehension way to avoid the previous pointed errors by @Mark in your code:

>>>counts = []
>>>counts = [item.count('C') for item in bins]
>>>counts
[1, 1, 1, 0]
  • Related