What’s the result of this script? ```s = "traceba...
# random
n
What’s the result of this script?
Copy code
s = "tracebacks_show_local"
s.strip("tracebacks_")
d
how_local
?
I think it's clear enough if look at the docs, but potentially problematic if you assume behavior. 😛
n
Alright, I was hoping it will trap someone (myself), the right way to do it with python>=3.9 is using the new built-in method
s.removeprefix
or
s.removesuffix
method. Maybe I should structure the problem like this.
Copy code
In [10]: "tracebacks_show_local".strip("tracebacks")
Out[10]: '_show_local'

In [11]: "tracebacks_show_local".strip("tracebacks_")
Out: ???
j
hahaha yeah,
strip
is a trap!!
n
What’s the clean way to do that then?
Copy code
keyword = "tracebacks_"
if s.startswith(keyword):
  s = s[len(keyword):]
or
Copy code
s = s.replace("tracebacks_", "")

?
Though the latter is more eager than the original purpose - I don’t really want to replace if it’s in the middle
a
Yeah, I’ve always done it like in you suggest with your first example. I didn’t even realise
removeprefix
existed until very recently
d
Oh, interesting, I didn't know of
removeprefix
n
Answer from ChatGPT (as always)
Copy code
def strip_prefix_suffix(string, prefix=None, suffix=None):
    """
    Strips the specified prefix and/or suffix from a string.

    Args:
        string (str): The input string.
        prefix (str, optional): The prefix to remove. Defaults to None.
        suffix (str, optional): The suffix to remove. Defaults to None.

    Returns:
        str: The modified string after stripping the prefix and/or suffix.
    """
    if prefix and string.startswith(prefix):
        string = string[len(prefix):]
    if suffix and string.endswith(suffix):
        string = string[: -len(suffix)]
    return string
👍🏼 1
👍 2
j
Copy code
if s.startswith(keyword):
  s = s[len(keyword):]
this does essentially the same as the C implementation https://github.com/python/cpython/pull/18939/files#diff-6878f29bbfb711dc7cd2a89b2b2941b1f900b6367d30181a2ff45460b591b04cR1202-R1218
👍 2
👍🏼 1
j
Copy code
s = "tracebacks_show_local"
s.partition("tracebacks_")[2]
Will split on the first 'tracebacks_' it encounters in the string and returns everything to the right of it
👍 1
Pretty sure it does what you want but I don't know what edge cases you might have
n
I want
s.removeprefix
, but it’s not available Python < 3.9, there are many ways that work but just less readable.
partition is also a good choice 🙂
d
I think it depends what you want to do. If you want an equivalent of
removeprefix
, I definitely prefer @Juan Luis’s answer, since it's explicit around it being the
prefix
(whereas
partition
could grab it from wherever, unless you also want to assert the first partition is empty).
n
All fair points 😁 I ask it in #C03QF15L1K9 for a reason, just curious what’s other thought : D