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")
'abc'

It works as expected. However in my test code:

filename = existing_source.name
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
3: tes.md

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

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

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

https://docs.astral.sh/ruff/rules/bad-str-strip-call/
https://docs.astral.sh/ruff/rules/strip-with-multi-characters/

2 Likes

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