Search code examples
pythonpython-3.xintegerbit

Converting integer to bits: TypeError: string indices must be integers - Python3


I'm trying to run this program that counts the ones in the bit representation of ints. Here is the code:

def count_bits(n):
    return bin(n).replace("0b", "")
            
bits = count_bits(3)
for i in bits:
    if bits[i] == 1:
        counter += 1
    else:
        counter = counter

But when I try to run it, I get the following error:

    if bits[i] == 1:
TypeError: string indices must be integers

Solution

  • You are iterating over bits, which is a string, so your i assumes the value of the characters in that string. You need to either convert all the characters to integers first, or find a better way to iterate over the bits.

    Simple solution:

    def count_bits(n):
        return list(map(int, bin(n).replace("0b", "")))
    

    Or you can use bits[int(i)].


    However, a better and more pythonic solution would be to do this mathematically using bitshifts and a generator:

    def bits(n):
        while n:
            yield n & 1
            n >>= 1
    
    counter = sum(bits(n))