Python Glossary Русский

Python 3.9+Strings (str)function

str.removesuffix

replacement

Return a copy with the given suffix removed if present, otherwise unchanged (Python 3.9+).

Syntax

s.removesuffix(suffix)

The usual job is stripping an extension, and that is exactly where rstrip('.py') corrupts data: it removes any trailing dots, p's and y's, turning 'happy.py' into 'ha'. Slicing by the suffix length by hand is no safer — it cuts the tail even when the suffix is absent, and an empty suffix leaves you with an empty string. For filenames, pathlib with stem and with_suffix is usually the better tool.

Examples

print('file.py'.removesuffix('.py'))   # → file
print('file'.removesuffix('.py'))      # → file
print('x__'.removesuffix('_'))         # → x_

See also

Open in the full glossarydocs.python.orgReport an inaccuracy