Python has a fantastic feature called slices
. It allows you to work with a list
, set
or string
by it’s index items.
E.g.:
string_sample = "hello world"
string_sample[:-1]
>>> "hello worl"
string_sample[-1]
>>> "d"
string_sample[3]
>>> "l"
You can also do things like:
string_sample[3:5]
>>> 'lo'
Or even in reverse!
string_sample[::-1]
>>> 'dlrow olleh'
A possible Java implementation
public String slice_start(String s, int startIndex) {
if (startIndex < 0) startIndex = s.length() + startIndex;
return s.substring(startIndex);
}
public String slice_end(String s, int endIndex) {
if (endIndex < 0) endIndex = s.length() + endIndex;
return s.substring(0, endIndex);
}
public String slice_range(String s, int startIndex, int endIndex) {
if (startIndex < 0) startIndex = s.length() + startIndex;
if (endIndex < 0) endIndex = s.length() + endIndex;
return s.substring(startIndex, endIndex);
}