-1
def hexdump(text, encoding='utf-8'):
    text_bytes = text.encode(encoding)
    for i in range(0, len(text_bytes), 16):
        chunk = text_bytes[i:i + 16]

What is text_bytes[i:i + 16] exactly doing?

martineau
  • 119,623
  • 25
  • 170
  • 301
srky
  • 350
  • 2
  • 4
  • 12

3 Answers3

1

It creates a substring from the i-th character to the (i + 16)th character. But notice that the (i + 16)th is not included.

For instance:

text_bytes = "foo-bar"
text_bytes[2: 5] will be "o-b"
Frightera
  • 4,773
  • 2
  • 13
  • 28
Mouhand
  • 26
  • 1
  • 4
0

Maybe this will answer your question: What does list[x::y] do?

So this question might be a duplicate.

Matthias
  • 21
  • 5
0

In python String is treated as a list in a sense that each character is an element of a list.

So, if

my_string = "abc"
my_list = ['a', 'b', 'c'] 

Iteration over my_string is seamlessly like iterating iterating over my_list. As some pointed out, see What does list[x::y] do? about this list slicing syntax

So regarding your question, text_bytes[i:i + 16] is treating text_bytes as list of its characters, slicing it, and returning the substring.

So, if we take the example above:

res_string = my_string[0:2] # == "ab" 
res_list = my_list[0:2] # == ['a', 'b'] 
YFl
  • 845
  • 7
  • 22