It seems to me that the desired behavior is closest to 'str.replace()' out
of all the options, just with the constraint of being limited to either the
start or the end of the string. (Thus the .lreplace() and .rreplace()
option suggested by Glenn earlier in the thread.)

The minimal change (which actually also seems pretty general) seems to me
to be adding *only_start* and *only_end* keyword arguments to
str.replace(), both defaulting to False. If, e.g., *only_start* is passed
True, each repetition of *old* at the start of *str* is replaced by a copy
of *new*, with the number of replacements limited by the existing optional
*count*. Similar behavior for *only_end*=True.  Probably best to raise a
ValueError(?) if both *only_start*=True and *only_end*=True?

Taking swapping a file extension as an example of a particular
transformation of interest, it would be achieved with something like
s.replace(".htm", ".html", only_end=True).

-Brian


----------------------------------------------------------------------
>
> Date: Tue, 2 Jul 2019 14:33:57 +1000
> From: Chris Angelico <ros...@gmail.com>
> Subject: [Python-Dev] Re: strip behavior provides inconsistent results
>         with certain strings
> To: python-dev <python-dev@python.org>
> Message-ID:
>         <CAPTjJmqFsWof=
> x64_vdym9jaj0z9n19te7dk+navvoxoih7...@mail.gmail.com>
> Content-Type: text/plain; charset="UTF-8"
>
> On Tue, Jul 2, 2019 at 2:28 PM Glenn Linderman <v+pyt...@g.nevcal.com>
> wrote:
> >
> >> A method could raise instead of returning the string as-is if the
> prefix is not really a prefix.  How often is this needed?  The most common
> end deletions are whitespace, which the current .strip handles correctly.
> >
> > raising wouldn't be helpful in most of the situations where I use this
> logic... it would require a more complex flow control than the  if
> startswith path in the current situation.
> >
> > Yes, I use strip more frequently, but if startswith: chop_prefix
> operation (and the other end too) happens an awful lot.
>
> If the method accepts a tuple of prefixes and will remove the first
> one found (or the longest, or whatever) and raises if none found, you
> could get the "chop only if present" behaviour by including an empty
> string as one of the possible prefixes.
>
> ChrisA
>
>
>
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/python-dev@python.org/message/SCZH4SYCM2Z2UXTKYMAIMHGRUKGKD2FU/

Reply via email to