ord() expected string, but int found

Question:

I’m having problem in the ord() def, my code is given below:

def write(data):
    for block_idx in list(range(0, len(data), 10)):
        chksum = 0
        for byte_idx in list(range(block_idx, 2)):
            chksum += ord(data[byte_idx])


write(b'123')
TypeError: ord() expected string of length 1, but int found
Asked By: andtompoi

||

Answers:

You’re providing b'123' to the function, which is bytes, that is why when you’re trying to get the byte of an specific position you’re getting an int. And when you’re passing an int to the ord(), the exception is thrown, because:

Given string of length 1, the ord() function returns
an integer representing the Unicode code point of the character when
the argument is a Unicode object, or the value of the byte when the
argument is an 8-bit string.

Use:

chksum += ord(chr(data[byte_idx]))
Answered By: devReddit

As the Python bytes documentation states:

While bytes literals and representations are based on ASCII text,
bytes objects actually behave like immutable sequences of integers

When b"123"[0] is called it returns an int which is an invalid argument to the builtin ord function.

You don’t even need to call ord in this case:

chksum += data[byte_idx]
Answered By: Maicon Mauricio
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.