Remove Literal Python Filename Suffixes with removesuffix

An asset importer turns running.png into an asset ID. Calling rstrip(".png") looks plausible, but produces runni instead of running. The importer has deleted part of the name, creating a risk that unrelated assets receive the same ID.

These examples use Python 3.9 or later and filename strings supplied by a manifest. They transform names in memory without renaming files.

Reproduce the Character Stripping Bug

Run this standalone example:

1
2
3
4
5
name = "running.png"
print(name.rstrip(".png"))
print(name.removesuffix(".png"))
# runni
# running

The argument to rstrip() is a set of removable characters. It keeps removing trailing characters while each belongs to that set. After the extension disappears, it also removes the final g and then n from running. It stops at i, which is outside the set, leaving runni.

Remove One Exact Ending

Literal removal has a narrower contract: removesuffix() removes one complete matching ending, while an absent ending leaves the value unchanged. Matching is case-sensitive. The Python string reference documents both removal methods.

1
2
3
4
5
6
7
names = ["jumping.png", "jumping.PNG", "jumping.png.png", "jumping.png.backup"]
for name in names:
    print(name.removesuffix(".png"))
# jumping
# jumping.PNG
# jumping.png
# jumping.png.backup

This preserves an internal occurrence of .png and removes only the last occurrence when it is at the end. Calling replace(".png", "") would also remove occurrences inside the name, which is inappropriate for this naming rule.

Require the Suffix Before Creating an ID

An optional cleanup operation and a required manifest field need different error policies. Save this helper as asset_id.py when every accepted name must end in lowercase .png and contain a nonempty ID before it:

1
2
3
4
5
6
7
8
9
def png_asset_id(name):
    if not isinstance(name, str):
        raise TypeError("asset name must be a string")
    if not name.endswith(".png"):
        raise ValueError("asset name must end with .png")
    asset_id = name.removesuffix(".png")
    if not asset_id:
        raise ValueError("asset ID must not be empty")
    return asset_id

Run this beside the helper:

1
2
3
4
5
6
from asset_id import png_asset_id

print(png_asset_id("jumping.png"))
print(png_asset_id("jumping.png.png"))
# jumping
# jumping.png

The explicit suffix check prevents an unexpected name from passing through unchanged. It does not inspect image contents or validate a filesystem path. If the manifest permits only basenames or a restricted ID alphabet, enforce those additional rules separately before using the ID as a destination path or database key.

Test Names That Ordinary Examples Miss

Save this as test_asset_id.py beside the helper and run python test_asset_id.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from asset_id import png_asset_id

for name, expected in [
    ("jumping.png", "jumping"),
    ("png.png", "png"),
    ("hero.png.png", "hero.png"),
    ("hero.backup.png", "hero.backup"),
    (" hero .png", " hero "),
]:
    assert png_asset_id(name) == expected

for name in ["", ".png", "hero", "hero.PNG", "hero.png.backup", "hero.png "]:
    try:
        png_asset_id(name)
    except ValueError:
        pass
    else:
        raise AssertionError(f"invalid name accepted: {name!r}")

try:
    png_asset_id(None)
except TypeError:
    pass
else:
    raise AssertionError("non-string name accepted")

assert "hero".removesuffix("") == "hero"
assert "hero"[:-len("")] == ""
print("Literal suffix checks passed.")

The png.png case catches a particularly destructive character-stripping mistake: all its characters belong to the stripping set. Repeated endings test the one-removal rule, while uppercase and trailing-space cases verify the manifest’s exact spelling policy. Spaces inside the ID remain intact because this helper does not trim them.

Keep the Removal Rule Explicit

For a generic suffix argument, an empty suffix is a useful boundary test. removesuffix("") preserves the original value, whereas a hand-written slice using [:-len(suffix)] becomes [:-0] and loses everything. PEP 616 explains the motivation for the dedicated methods and their empty-affix behavior.

The corresponding removeprefix() method handles one literal beginning. Use these methods when the format specifies a known string at a known boundary. Keep rstrip() for removing a set of trailing characters, such as whitespace, when that is the intended operation.

This helper deliberately accepts hero.png.png as the ID hero.png. Reject repeated extensions explicitly if the manifest forbids them. Removing more suffixes in a loop would implement a different naming policy and could merge distinct names. Likewise, preserve case unless the manifest defines a case-insensitive identity rule; an ad hoc lowercase conversion can collapse names that a later consumer treats as distinct.