简体   繁体   中英

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 int s. 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

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))

Because you iterate over bits , which is a string, i will also be a string, and you compare it to 1, which is an int . You need to either do something like this

def count_bits(n):
    return bin(n).replace("0b", "");

bits = count_bits(3);
for i in range(len(bits)):
    if bits[i] == 1:
        counter += 1;
    else:
        counter = counter;

so i will be an int and you compere it to int 1 , or something like this

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;

so i will be a string , like originally, but you compare it to a string "1" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM