[Tutor] Replacing part of a URL
anand.shashwat at gmail.com
Sun Feb 21 00:15:12 CET 2010
>>> url = 'http://www.somesite.com/some/path/to/something.html'
>>> var = 'anotherthing'
>>> i = url.rfind('/') + 1
>>> j = url.rfind('.')
>>> if i < j:
... newurl = url[:i] + var + url[j:]
... newurl = url[:i] + var
Changing the url to 'http://www.somesite.com/some/path/to/something' we get
newurl as 'http://www.somesite.com/some/path/to/anotherthing'
However if you are absolutely sure the pattern is '
http://www.somesite.com/some/path/to/something.html' , then you can simply
write one-liner as:
>>> url[:url.rfind('/') + 1] + var + url[url.rfind('.'):]
Literally the same stuff. I don't think you need regex for such simple
On Sun, Feb 21, 2010 at 4:04 AM, Lao Mao <laomao1975 at googlemail.com> wrote:
> I need to be able to replace the last bit of a bunch of URLs.
> The urls look like this:
> They may be of varying lengths, but they'll always end with
> I want to take the "something" and replace it with something else.
> My current plan is to simply do a string.split("/")[-1]
> and then another .split('.') to result in ['something', 'html'], and then
> replace sometihing, and join them together again.
> But - wouldn't it make more sense to do this with re.sub?
> In which case, how would I specify only the bit between the last / and the
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor