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?
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?
is not quite right.
What you actually would need to write is
, and it looks pretty succinct IMHO.
However, my personal preference is this option because it uses only one parameter:
In one line:
Since it seems like nobody has pointed this on out yet:
This should be more efficient than the methods using
split()
as no new list object is created, and this solution works for strings with several dots.I want to repeat this answer as the most expressive way to do it. Of course, the following would take less CPU time
However, if CPU is the bottle neck why write in Python?
When is CPU a bottle neck anyway?? in drivers , maybe.
The advantages of using regular expression is code reusability. What if you next want to remove '.me' , which only has three characters?
Same code would do the trick.
strip
doesn't mean "remove this substring".x.strip(y)
treatsy
as a set of characters and strips any characters in that set from the ends ofx
.Instead, you could use
endswith
and slicing:Or using regular expressions: