9. Use removeprefix and removesuffix

Use removeprefix() and removesuffix() instead of manual slicing when trimming known text.

The dedicated methods encode the exact intent and avoid off-by-one or accidental-match bugs from manual slicing. They are also easier to read because a reviewer does not have to reconstruct why a particular slice index was chosen.

Note

Python 3.9+

9.1. Don’t do this

1filename = 'report.csv'
2if filename.endswith('.csv'):
3    filename = filename[:-4]

9.2. Do this

1filename = 'report.csv'
2filename = filename.removesuffix('.csv')