-2

In my code there is a line:

charInBinary = str(bin(ord(MESSAGE[i])))[2:]

What is [2:] need for?

3 Answers3

2

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.

fireshadow52
  • 5,888
  • 2
  • 29
  • 45
0

bin returns a string with a leading 0b prefix. The [2:] is snipping off the prefix, leaving only the binary digits

pat
  • 12,485
  • 1
  • 22
  • 49
0

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
Sharim Iqbal
  • 2,724
  • 1
  • 4
  • 24