python: rstrip one exact string, respecting order python: rstrip one exact string, respecting order python python

python: rstrip one exact string, respecting order


You're using wrong method. Use str.replace instead:

>>> "Boat.txt".replace(".txt", "")'Boat'

NOTE: str.replace will replace anywhere in the string.

>>> "Boat.txt.txt".replace(".txt", "")'Boat'

To remove the last trailing .txt only, you can use regular expression:

>>> import re>>> re.sub(r"\.txt$", "", "Boat.txt.txt")'Boat.txt'

If you want filename without extension, os.path.splitext is more appropriate:

>>> os.path.splitext("Boat.txt")('Boat', '.txt')


Starting with Python 3.9, use .removesuffix():

"Boat.txt".removesuffix(".txt")

On earlier versions of Python, you'll have to either define it yourself:

def removesuffix(s, suf):    if suf and s.endswith(suf):        return s[:-len(suf)]    return s

(you need to check that suf isn't empty, otherwise removing an empty suffix e.g. removesuffix("boat", "") will do return s[:0] and return "" instead of "boat")

or use regex:

import resuffix = ".txt"s = re.sub(re.escape(suffix) + '$', '', s)


In Python 3.9, as part of PEP-616, you can now use the removeprefix and removesuffix functions:

>>> "Boat.txt".removeprefix("Boat")>>> '.txt'>>> "Boat.txt".removesuffix(".txt")>>> 'Boat'