I have the following code:
url = 'abcdc.com'
print(url.strip('.com'))
I expected: abcdc
I got: abcd
Now I do
url.rsplit('.com', 1)
Is there a better way?
See How do the .strip/.rstrip/.lstrip string methods work in Python? for a specific explanation of what the first attempt is doing.
stripdoesn’t mean "remove this substring".x.strip(y)treatsyas a set of characters and strips any characters in that set from both ends ofx.On Python 3.9 and newer you can use the
removeprefixandremovesuffixmethods to remove an entire substring from either side of the string:The relevant Python Enhancement Proposal is PEP-616.
On Python 3.8 and older you can use
endswithand slicing:Or a regular expression: