I have a variable conts which contains the contents of a binary file (read it with rb as mode). Now when I try to get pieces of the string via slicing I would expect to see the proper length for the variables (and obviously the contents, too), but I don’t.
Here is code with which I can reproduce this and I am out of ideas what is going on here:
hdr1, hdr2 = conts[0:6], conts[10:7]
print "----------------"
print len(conts)
print len(hdr1)
print len(hdr2)
print len(conts)
print "----------------"
print type(hdr1)
print type(hdr2)
print type(conts)
The output I get is however:
----------------
32174321
6
0
32174321
----------------
<type 'str'>
<type 'str'>
<type 'str'>
What’s going on here? I thought slicing would create a new string for each slice?
Python version: 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
Note: the four-byte gap between the slices is intentional. The problem is rather that the second slice returns a zero-length string, even though there would be enough data. I found no documentation that pieces (when slicing) need to be adjacent.
Edit: after realizing my error: I intended to get from a string longer than 17 bytes the bytes 0 to 6 and the bytes 10 to 17.
The reason this is an empty string is because you didn’t mention that you wanted a negative step for the slicing, assuming you did mean to slice backwards.
Will do what you want, notice the
-1that lets python know that you want to step backwards when slicing instead of forwards.As an aside, this also leads to an easy way to reverse strings:
The format of slicing is:
[start_index:end_index:step]From your edit I can see that this answer may be redundant for your purpose, but it is good information for you to know so I will leave it up.
Here is how you would do what you said in your edit: