String.substring() and List.getRange() are somewhat verbose, but very common operations. Python's slice operator provides an easy-to-read notation to replace these.
Examples of substring() and slice [:]
string.substring(a) -> string[a:]
string.substring(a, b) -> string[a:b]
string.substring(0, a) -> string[:a]
_Removed Type-Defect label._
_Added Type-Enhancement, Area-Library, Triaged labels._
_This comment was originally written by @jinmingjian_
great. more my idea is to enhance the slicing operator to an general indexing technology for array like objects, like:
1: a:b = a:1:b = a,a+1,...,b
2: a:2:b = a, a+2,...b
3: a:-1:b = a, a-1,...b
4: [:,a:b] = [1,a:b],[2,a:b]...
_This comment was originally written by thebinarysearc...@gmail.com_
I would argue that it is not easier to read. substring says what it is doing in English, whereas string[3:2] is symbolism.
_This comment was originally written by @jinmingjian_
yes or no. Yes, because this is just a syntax magic. No, ":" for slicing is the tradition of numerical computing software[1]. My suggestion is more mathematical. That is, it does not pursue symbolism, it pursues intuition. The ":" is used for generating a vectorized index(i.e.,1D array). And,
So,
[3:2] -> [3:1:2], 3 can not reach 2 by step 1 -> nothig. may want [3:-1:2]
[:a] -> not syntax right, may want [0:a]
_This comment was originally written by @jinmingjian_
numerical computing software -> numerical computing language, more exactly.
_This comment was originally written by @seaneagan_
I think this would require a user-definable operator:
List#getRange becomes:
List<T> operator :;
String#substring becomes:
String operator :;
And it would probably make sense to support slicing then as well, by replacing List#setRange with:
List<T> operator [:]= (List other, [int first, int last]);
List#removeRange also becomes unnecessary, instead of:
list.removeRange(0, 5);
just do:
list[:5] = [];
// or
list[:5] = null;
Reassigning to language. This requires new syntax and is thus not a library bug.
_Removed Area-Library label._
_Added Area-Language label._
Issue #8977 has been merged into this issue.
Please support negative indexes (relative from the end) as Python does.
At the very least make String.substring() accept negative indexes.
_Set owner to @gbracha._
_Removed Priority-Medium label._
_Added Priority-Low, Accepted labels._
It has been 8.5 years. substring method should accept negative values.
Yeah, this is really weird since even Javascript String.prototype.slice() takes negative values.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice
Any news on this? Is it ever going to happen? Doesn't sound too difficult. Is it?
Most helpful comment
Please support negative indexes (relative from the end) as Python does.
At the very least make String.substring() accept negative indexes.