Nok Lam Chan
05/23/2023, 1:21 PMs = "tracebacks_show_local"
s.strip("tracebacks_")
Deepyaman Datta
05/23/2023, 1:23 PMhow_local
?Nok Lam Chan
05/23/2023, 1:29 PMs.removeprefix
or s.removesuffix
method.
Maybe I should structure the problem like this.
In [10]: "tracebacks_show_local".strip("tracebacks")
Out[10]: '_show_local'
In [11]: "tracebacks_show_local".strip("tracebacks_")
Out: ???
Juan Luis
05/23/2023, 1:30 PMstrip
is a trap!!Nok Lam Chan
05/23/2023, 1:32 PMkeyword = "tracebacks_"
if s.startswith(keyword):
s = s[len(keyword):]
or
s = s.replace("tracebacks_", "")
?
Antony Milne
05/23/2023, 1:37 PMremoveprefix
existed until very recentlyDeepyaman Datta
05/23/2023, 1:37 PMremoveprefix
Nok Lam Chan
05/23/2023, 1:39 PMdef 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
Juan Luis
05/23/2023, 1:39 PMif 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-R1218Jannic Holzer
05/23/2023, 1:40 PMs = "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 itNok Lam Chan
05/23/2023, 1:42 PMs.removeprefix
, but it’s not available Python < 3.9, there are many ways that work but just less readable.Deepyaman Datta
05/23/2023, 1:45 PMremoveprefix
, 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).Juan Luis
05/23/2023, 1:46 PMNok Lam Chan
05/23/2023, 1:53 PM