Skip to content

Use String Remove Affix

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: use-string-remove-affix

Section titled “Sourcery refactoring id: use-string-remove-affix”

Replaces string slicing with the Python 3.9 features removesuffix and removeprefix.

if text.startswith("Hello, "):
text = text[7:]
if text.endswith(" World!"):
text = text[: -len(" World!")]
text = text.removeprefix("Hello, ")
text = text.removesuffix(" World!")

This refactoring is motivated by PEP 616. As stated in the documentation, using these methods confers several advantages, including being more robust to user error, more performant, and more descriptive.