In my code there is a line:
charInBinary = str(bin(ord(MESSAGE[i])))[2:]
What is [2:] need for?
In my code there is a line:
charInBinary = str(bin(ord(MESSAGE[i])))[2:]
What is [2:] need for?
The [2: ]
is slice notation, and since that's being performed on a str
, it means that you're retrieving all of the characters of the string starting at index 2. In this case, that's getting rid of 0b
.
bin
returns a string with a leading 0b
prefix. The [2:]
is snipping off the prefix, leaving only the binary digits
It's a simple question.
Without [2:]
your output starts with 0b
, So for removing this we use this [2:]
charInBinary = str(bin(ord(MESSAGE[i])))
print(charInBinary) # 0b111111
# WIth [2:]
charInBinary = str(bin(ord(MESSAGE[i])))[2:]
print(charInBinary) # 111111