Issues with string splicing in python when using range and negative steps -
Issues with string splicing in python when using range and negative steps -
i playing around python string splicing , ran behavior of python not understand. lets have string , spliced in 3 different ways:
str = "stackoverflow" splicedstr = str[2:6] #this spliced string equal 'ackove' splicedstr = str[2:8:2] #this spliced string equal 'akv' splicedstr = str[2:8:-2] #this spliced string equal '' i understand first 2 splicing. lastly example, have negative step count, why wouldn't equal 'vka'?
the piece you're looking is:
>>> s[-7:1:-2] 'vka' which also:
>>> s[6:1:-2] 'vka' note start @ first index provided , go until nail (or bigger than) sec index provided. 3rd index stride.
in case, start @ 8 (which bigger 2) end empty string.
i think expected, negative stride, first index position right hand side of string. isn't case -- negative indices count left side of string.
as usual, the official language reference states more formally (and correctly) can.
the piece of s j step k defined sequence of items index x = + n*k such 0 <= n < (j-i)/k. in other words, indices i, i+k, i+2*k, i+3*k , on, stopping when j reached (but never including j). if or j greater len(s), utilize len(s). if or j omitted or none, become “end” values (which end depends on sign of k). note, k cannot zero. if k none, treated 1.
python
Comments
Post a Comment