Trying to understand why taking the index of a bytes object returns an int that you can't decode, but a slice returns a bytes object that you can. This seems un-intuitive. When you do the same operation with a string, taking an index at the string position still returns a string.
Working on the Cryptopals challenges, I'm trying to iterate over a byte array to do frequency analysis of an XORed string to count the occurrence of the number of plain text letters. I thought I could do the following, but I'm getting 'int' object has not attribute 'decode' error. From reading the Python docs, that makes sense, a byte array is a mutable sequence of integers, but when testing in the interpreter I was expecting different behavior.
str_a = bytearray(b'\x1b77316?x\x15\x1b\x7f+x413=x9x(7-6<x7>x:9;76')
for x in str_a:
_ = x.decode('ascii').upper()
if _ in counts:
counts[_] += 1
If I set a variable to a single byte, I can call decode() on it. I figured I could then iterate over all bytes in a byte string and decode in the same way (hence the loop above). But, since r[0] is an int, that doesn't work. But then if I take r[0:1], it does? I realize I could just call chr(r[0]), but I figured if r.decode() works, r[0].decode() should work too.
>>> r = b'A'
>>> type(r)
<class 'bytes'>
>>> r.decode('ascii')
'A'
>>> r[0:1]
b'A'
>>> r[0:1].decode('ascii')
'A'
>>> type(r[0])
<class 'int'>
>>> r[0]
65
>>> r[0].decode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'decode'
String Example
>>> x = 'AB'
>>> type(x)
<class 'str'>
>>> x[0]
'A'
>>> type(x[0])
<class 'str'>