-1
header_text = f.read(header_text_size)[:-2].decode('utf-16').encode('utf-8')

What is the meaning of [:-2] in this Python code? I want to translate this into Java, and I need to know what it does.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
feemung
  • 3
  • 1
  • 1

2 Answers2

0

Slice from the sequence, the first element (inclusive) to the 2nd to last (exclusive).

For example:

x = [0, 1, 2, 3, 4, 5]
y = x[:-2]
print(y)  # [0, 1, 2, 3]

Slices always include the "start" argument, and exclude the "stop" argument.

Also, negative indices to slices always represent counting backwards from the end. (-1 means the last index, -2, means the second to last, etc).

More on slice notation

Community
  • 1
  • 1
jedwards
  • 29,432
  • 3
  • 65
  • 92
0

a_list[:-2] drops the last 2 elements from the list a_list. a_string[:-2] drops the last 2 chars from the string a_string (probably your case):

>>> s = 'some string with last chars 012'
>>> s[:-2]
'some string with last chars 0'
Dan Cornilescu
  • 39,470
  • 12
  • 57
  • 97