Strange behavior of str's rstrip

This is my most strange bug I have ever meet…

when I run the below code in python interpreter:

>>> x = "abc.txt"
>>> x.rstrip(".txt")

It works as expected. However in my test code:

filename =
print(f"\t 1: {filename}/{type(filename)} {self.source_suffix}/{type(self.source_suffix)}")
filename = filename.rstrip(self.source_suffix)
print(f"\t 2: {filename}")
filename += self.target_suffix
print(f"\t 3: {filename}")

prints this:

1: test.txt/<class 'str'> .txt/<class 'str'>
2: tes

I really don’t know what is going on :confused: Why it “swallowed” one “t” in “test”?

>>> x = "abc.txt"
>>> x.rstrip("t.x")

P.S. using a linter like ruff or flake8 can help catch hiccups like this:


Thanks! Now I feel so greenhorn now :blush: I always pointed others to a documentation, but this time it was me that forgot this.

1 Like

Since Python 3.9 there’s the .removesuffix method which does what you want.

1 Like