2

I could understand clearly the rng[0, 0] and rng[1], but why? Why rng[:, 3:] slicing to be $D$1:$D$5? And why rng[1:3, 1:3] to be $B$2:$C$3, I cannot understand the rule of slicing.

Range indexing/slicing
Range objects support indexing and slicing, a few examples:

rng = xw.Book().sheets[0].range('A1:D5')
User42
  • 970
  • 1
  • 16
  • 27
Sure Ley
  • 21
  • 3
  • just google it and you will immediately find rules for slicing with numerous examples. http://www.dotnetperls.com/slice-python – a.smiet Aug 30 '16 at 11:41
  • Thank you for your good webside, I'm learning it, thanks again. :) – Sure Ley Aug 30 '16 at 11:44
  • Forgot to mention: Don't forget that Python indexing starts with 0 and not 1 – a.smiet Aug 30 '16 at 11:46
  • I just overview your web, but I still can't figure out my issue, and I don't know how to search the answer from Google. Would you mind help me figure this question out? Thank you. – Sure Ley Aug 30 '16 at 11:49
  • I know some basic rules about python, but I never meet slice way like this rng[1:3, 1:3], it include ':' and ',' – Sure Ley Aug 30 '16 at 11:51

1 Answers1

1

I'll give it a go. Because in square brackets, indexing starts at 0 *. So for a 1-based indexing system, consider [1:3, 1:3] as (2:4, 2:4). Also bear in mind that the value after : is not included, so inclusively (2:4, 2:4) is (2:3, 2:3). The second Excel Column is B, the third C, and the second Excel row is 2 and the third 3. Hence the range is B2:C3.

IMO a horrible choice of example!

Given a range A1:D5, slicing with rng[:, 3:] means all rows and fourth column to end column, hence D1:D5.

Taking just the column element [1:3] from the same range (A1:D5). The slicing starts (including) the second index element (0 first, 1 second) ie B and continues to immediately before the fourth index element (A, B, C, D). Hence B:C.

SO39226421 example

* For why start at 0 there are details here.

Community
  • 1
  • 1
pnuts
  • 58,317
  • 11
  • 87
  • 139
  • 1
    Sorry, I was thinking your idea almost 30mins....but still couldn't understand.....is there anyway more clear? Sorry for my bad IQ.....:) – Sure Ley Aug 30 '16 at 12:43
  • 1
    I got it now!!!! Thank you very much! I thouht it would more clear[1:3,1:3]means[row2 to row 3, column 2 to column 3] – Sure Ley Aug 30 '16 at 12:53
  • Thank you pnuts, you helped me lot, I totally understand now :) – Sure Ley Aug 30 '16 at 15:05