Python Forum

Full Version: Remove from end of string up to and including some character
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I'm trying to take some string, stri_ , and iterate through it until I find a particular character. Then, I will update the stri_ to be stri_ with that character and everything after it removed.

#  Working with url_ , a string of any length
url_ = url_[:url_.find(".")]

#  For url_ == "wikipedia.com", url_ should become "wikipedia".
print(url_)  # wikipedia
The above works fine in most cases, however I ran into problems with the below.

#  Working with url_ , a string of any length
url_ = url_[:url_.find(".")]

#  For url_ == "en.wikipedia.com", url_ should become "en.wikipedia".
print(url_)  # en
Is there any way I can do something similar to rstrip(), but instead of removing a single character, remove every character rstrip() checked before it found "." ie. the last "." in the string?

Thanks,

K
You were on the right lines with rstrip. Instead use rsplit(), which takes two arguments. A delimiter and a maxsplit.

result = url_.rsplit('.', 1)[0]
It doesn't matter how many '.' you have at the front of the string, it will only every remove anything after the last '.':
Output:
>> a = "wikipedia.com" >> print(a.rsplit(".", 1)[0]) >> wikipedia >> a = "en.wkikipedia.com" >> print(a.rsplit(".", 1)[0]) >> en.wkikipedia >> a = "en.something.somethingelse.wikipedia.com" >> print(a.rsplit(".", 1)[0]) >> en.something.somethingelse.wikipedia
change url_find('.') to url_rfind('.') will give you what you want
Output:
>>> url = 'wikipedia.com' >>> print(url[:url.rfind('.')]) wikipedia >>> url = 'en.wikipedia.com' >>> print(url[:url.rfind('.')]) en.wikipedia