How to get everything after last slash in a URL?

121

How can I extract whatever follows the last slash in a URL in Python? For example, these URLs should return the following:

URL: http://www.test.com/TEST1
returns: TEST1

URL: http://www.test.com/page/TEST2
returns: TEST2

URL: http://www.test.com/page/page/12345
returns: 12345

I've tried urlparse, but that gives me the full path filename, such as page/page/12345.

This question is tagged with python parsing url

~ Asked on 2011-08-31 07:23:22

The Best Answer is


270

You don't need fancy things, just see the string methods in the standard library and you can easily split your url between 'filename' part and the rest:

url.rsplit('/', 1)

So you can get the part you're interested in simply with:

url.rsplit('/', 1)[-1]

~ Answered on 2011-08-31 07:28:00


74

One more (idio(ma)tic) way:

URL.split("/")[-1]

~ Answered on 2011-08-31 07:31:17


Most Viewed Questions: