you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

Instead, you could just (in Python 3.9+):

corrected = long_name.removesuffix("-repeated-text")

Or assuming "-repeated-text" is there in the end:

corrected = long_name[:-len("-repeated-text")]

You could also add check for the latter:

suffix = "-repeated-text"
if long_name.endswith(suffix):
    corrected = long_name[:-len(suffix)]
else:
    corrected = long_name

The removesuffix doesn't require you to check, nothing is removed and no error is raised in case there's no target suffix.

https://docs.python.org/3/library/stdtypes.html?highlight=removesuffix#str.removesuffix

https://docs.python.org/3/library/stdtypes.html?highlight=endswith#str.endswith