Re: strip behavior provides inconsistent results with certain strings
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 <rosuav@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+naVvoXOih7SJQ@mail.gmail.com> Content-Type: text/plain; charset="UTF-8"
On Tue, Jul 2, 2019 at 2:28 PM Glenn Linderman <v+python@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
participants (1)
-
Brian Skinn