-2

In my code there is a line:

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

What is [2:] need for?

Bảo Chi
  • 7
  • 1
  • 1

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
  • 6,298
  • 2
  • 30
  • 46
0

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

pat
  • 12,587
  • 1
  • 23
  • 52
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
codester_09
  • 5,622
  • 2
  • 5
  • 27