Re: Slices by length

MRAB <[email protected]>
Newsgroups gmane.comp.python.general
Message-ID <[email protected]>
On 2025-09-06 13:47, Rob Cliffe via Python-list wrote:
> I quite often find myself writing expressions of the form
>       someString[x : x+n]
> where n is often an int and x may be an int, a variable, or a (possibly
> complicated) expression.
> It would be more natural to be able to specify the slice not by its
> startpoint and ENDPOINT,
> but by its startpoint and LENGTH, particularly when x is a long
> expression and has to be repeated or pre-stored in a variable.
> I have worked with languages that had this facility, and I miss it.
> The possible syntaxes are restricted by the need to avoid ambiguity with
> existing valid code.
> It could be for example
>       someString[x ! n]
> (of course, x and n could be arbitrary expressions).
> One point to be decided would be whether negative n would produce
>       (a) an empty string, so that s[x ! n] was always the same as s[x :
> x+n]
>       (b) a slice ending at x, e.g. "01234567"[4!-3] would equal "123"
> (or less plausibly "321").
> I don't have a strong opinion on this; there may be good reasons for
> preferring one to another.
> Does anybody think this is a good idea?
>
I'm not happy about the syntax.
How about `someString[x +: n]`?

As for a negaitve length, it should probably return an empty string 
given that `someString[x : x+n]` returns an empty string if `n` is negative.

The syntax would leave open the possibility of adding `someString[x -: 
n]` in the future for option b.

On a related note, a quick search revealed that the D programming 
language lets you write `someString[x .. $]` where `$` in that context 
is the length. That lets you write `someString[x .. $ - n]`. In Python 
that could be `someString[x : $ - n]`, equivalent to `someString[x : 
len(someString) - n]`, even if `n` is 0.
-- 
https://mail.python.org/mailman3//lists/python-list.python.org
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.