Skip to content

Str Prefix Suffix

Sourcery refactoring id: str-prefix-suffix

Description

Replace explicit str prefix/suffix check with call to startswith/endswith.

Before

name[:8] == "Sourcery"
name[-8:] == "Sourcery"

After

name.startswith("Sourcery")
name.endswith("Sourcery")

Explanation

When we read code like name[:8] == 'Sourcery' it takes a moment to understand exactly what it is doing. Instead when we read name.startswith('Sourcery') or name.endswith('Sourcery') it is immediate clear what the intent of the code is. Additionally we don't have to manually count the length of the prefix and check it is the same as the slice end; if we ever change the prefix we are less likely to make a mistake.

Back to top