diff --git a/boltons/strutils.py b/boltons/strutils.py index 60f4652f..1d43f2b0 100644 --- a/boltons/strutils.py +++ b/boltons/strutils.py @@ -57,7 +57,7 @@ 'iter_splitlines', 'indent', 'escape_shell_args', 'args2cmd', 'args2sh', 'parse_int_list', 'format_int_list', 'complement_int_list', 'int_ranges_from_int_list', 'MultiReplace', - 'multi_replace', 'unwrap_text'] + 'multi_replace', 'unwrap_text', 'removeprefix'] _punct_ws_str = string.punctuation + string.whitespace @@ -1273,3 +1273,17 @@ def unwrap_text(text, ending='\n\n'): if ending is None: return all_grafs return ending.join(all_grafs) + +def removeprefix(text: str, prefix: str) -> str: + r""" + Remove `prefix` from start of `text` if present. + + Backport of `str.removeprefix` for Python versions less than 3.9. + + Args: + text: A string to remove the prefix from. + prefix: The string to remove from the beginning of `text`. + """ + if text.startswith(prefix): + return text[len(prefix):] + return text diff --git a/tests/test_fileutils.py b/tests/test_fileutils.py index 1c00ab73..81987b0b 100644 --- a/tests/test_fileutils.py +++ b/tests/test_fileutils.py @@ -6,6 +6,7 @@ from boltons import fileutils from boltons.fileutils import FilePerms, iter_find_files +from boltons.strutils import removeprefix BOLTONS_PATH = os.path.dirname(os.path.abspath(fileutils.__file__)) @@ -31,7 +32,7 @@ def test_fileperms(): def test_iter_find_files(): def _to_baseless_list(paths): - return [p.lstrip(BOLTONS_PATH) for p in paths] + return [removeprefix(p, BOLTONS_PATH).lstrip(os.path.sep) for p in paths] assert 'fileutils.py' in _to_baseless_list(iter_find_files(BOLTONS_PATH, patterns=['*.py']))