Skip to content

slice-to-remove-prefix-or-suffix (FURB188)

Derived from the refurb linter.

Fix is always available.

This rule is unstable and in preview. The --preview flag is required for use.

What it does

Checks for the removal of a prefix or suffix from a string by assigning the string to a slice after checking .startswith() or .endswith(), respectively.

Why is this bad?

The methods str.removeprefix and str.removesuffix, introduced in Python 3.9, have the same behavior and are more readable and efficient.

Example

filename[:-4] if filename.endswith(".txt") else filename
if text.startswith("pre"):
    text = text[3:]

Use instead:

filename = filename.removesuffix(".txt")
text = text.removeprefix("pre")