On Sun, Apr 4, 2021 at 1:10 AM <janfrederik.konopka@gmail.com> wrote:
- The best alternative currently is str.partition(sep) but such code is not very readable, plus most users do not know about it, as proven by the StackOverflow link. Note that if not found this defaults to the original str for substringAfter, and an empty string for substringBefore: substringAfter = lambda s, sep: s.partition(sep)[2] substringBefore = lambda s, sep: s.partition(sep)[0]
If the biggest problem is "people don't know about it", then adding a new function isn't going to solve that :)
As an alternative, I think str.partition(sep) could be changed to return a NamedTuple rather than a simple tuple.
Not sure what the performance implications would be, but that seems pretty reasonable. But what I'd recommend is using unpacking: before, sep, after = s.partition(sep) Job done. Everything's clear, you can use "if s:" to find out if the separator was present or not, and you can define the precise semantics on not-found very easily. ChrisA