165

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.

5
  • 2
    If the URL might contain querystrings like ...?foo=bar and you don't want this; I'd suggest use urlparse in combination with naeg's basename-suggestion.
    – plundra
    Aug 31, 2011 at 7:31
  • URLs can end with a slash. If you need http://www.test.com/TEST1/ to return TEST1 then all these answers aren't for you.
    – user3064538
    Oct 6, 2020 at 1:19
  • I'm a little disappointed that no one used the url of this question in their example :~( Aug 27, 2021 at 4:02
  • @Boris: Not anymore - since your answer (and now also mine). ;-)
    – lcnittl
    Dec 22, 2021 at 10:11

14 Answers 14

343

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]
6
  • 16
    url.rsplit('/', 1) returns a list, and url.rsplit('/', 1)[-1] is the bit after the last slash.
    – Hugo
    Oct 13, 2015 at 12:26
  • 5
    Another way to do would be: url.rsplit('/', 1).pop() Mar 2, 2018 at 17:55
  • 20
    WARNING: This basic trick breaks completely on URLs such as http://www.example.com/foo/?entry=the/bar#another/bar. But basic parsing like rsplit is okay if you are absolutely certain there will never be any slashes in your query or fragment parameters. However, I shudder to think of how many codebases actually contain this rsplit code and its associated bug with query handling. People who want ABSOLUTE SECURITY AND RELIABILITY should be using urllib.parse() instead! You can then use the path value that it returns and split THAT to ensure that you've split ONLY the path. May 31, 2020 at 7:26
  • 14
    CODE: An example of how to implement the better method: from urllib.parse import urlparse; p = urlparse("http://www.example.com/foo.htm?entry=the/bar#another/bar"); print(p.path.rsplit("/", 1)[-1]) Result: foo.htm May 31, 2020 at 7:37
  • 1
    @Caterpillaraoz I count two non-accepted answers here that suggest exactly this for years now :)
    – tzot
    Sep 20, 2021 at 8:51
94

One more (idio(ma)tic) way:

URL.split("/")[-1]
2
  • 3
    Yes this is more straightforward than using rsplit. Aug 6, 2019 at 15:50
  • plus 1 for the funny comment haha Mar 16, 2022 at 2:13
16

rsplit should be up to the task:

In [1]: 'http://www.test.com/page/TEST2'.rsplit('/', 1)[1]
Out[1]: 'TEST2'
0
13

urlparse is fine to use if you want to (say, to get rid of any query string parameters).

import urllib.parse

urls = [
    'http://www.test.com/TEST1',
    'http://www.test.com/page/TEST2',
    'http://www.test.com/page/page/12345',
    'http://www.test.com/page/page/12345?abc=123'
]

for i in urls:
    url_parts = urllib.parse.urlparse(i)
    path_parts = url_parts[2].rpartition('/')
    print('URL: {}\nreturns: {}\n'.format(i, path_parts[2]))

Output:

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

URL: http://www.test.com/page/page/12345?abc=123
returns: 12345
2
  • 2
    Using urlparse is the right answer, but this will return "" if your url ends with a /.
    – user3064538
    Oct 6, 2020 at 1:24
  • 2
    using i.rstrip('/') would solve the empty path when ending in /
    – neves
    Nov 26, 2021 at 21:29
13

You can do like this:

head, tail = os.path.split(url)

Where tail will be your file name.

1
  • 1
    This won't work on systems where the path separator is not "/". One of the notes in the os.path docs mentions a posixpath, but I couldn't import it on my system: "you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats. They all have the same interface: posixpath for UNIX-style paths"
    – aschmied
    Sep 24, 2021 at 19:48
10
os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
>>> folderD
2
  • 1
    this also works: from pathlib import Path print(f"Path(redirected_response.url).stem: {Path(redirected_response.url).stem!r}") Jun 25, 2020 at 8:35
  • URLs aren't file paths, they can contain a ?query=string or a #fragment after the path.
    – user3064538
    Nov 18, 2020 at 22:07
5

Here's a more general, regex way of doing this:

    re.sub(r'^.+/([^/]+)$', r'\1', url)
2
  • 1
    can you explain it a bit? Jan 13, 2020 at 16:25
  • @sandoronodi. Thanks for your solution. If the url is embedded in a long string, then how can I keep the information after the last /? Thank you.
    – Sophia
    Jun 25 at 21:40
4

First extract the path element from the URL:

from urllib.parse import urlparse
parsed= urlparse('https://www.dummy.example/this/is/PATH?q=/a/b&r=5#asx')

and then you can extract the last segment with string functions:

parsed.path.rpartition('/')[2]

(example resulting to 'PATH')

2
  • 1
    or we can use parsed.path.rpartition('/')[-1] to get the last segment
    – Franz Wong
    May 11, 2022 at 4:14
  • 1
    .partition always returns a 3-element-tuple, so [-1] is [2].
    – tzot
    May 12, 2022 at 10:11
4

Use urlparse to get just the path and then split the path you get from it on / characters:

from urllib.parse import urlparse

my_url = "http://example.com/some/path/last?somequery=param"
last_path_fragment = urlparse(my_url).path.split('/')[-1]  # returns 'last'

Note: if your url ends with a / character, the above will return '' (i.e. the empty string). If you want to handle that case differently, you need to strip the last trailing / character before you split the path:

my_url = "http://example.com/last/"
# handle URL ending in `/` by removing it.
last_path_fragment = urlparse(my_url).path.rstrip('/', 1).split('/')[-1]  # returns 'last'
3

The following solution, which uses pathlib to parse the path obtained from urllib.parse allows to get the last part even when a terminal slash is present:

import urllib.parse
from pathlib import Path

urls = [
    "http://www.test.invalid/demo",
    "http://www.test.invalid/parent/child",
    "http://www.test.invalid/terminal-slash/",
    "http://www.test.invalid/query-params?abc=123&works=yes",
    "http://www.test.invalid/fragment#70446893",
    "http://www.test.invalid/has/all/?abc=123&works=yes#70446893",
]

for url in urls:
    url_path = Path(urllib.parse.urlparse(url).path)
    last_part = url_path.name  # use .stem to cut file extensions
    print(f"{last_part=}")

yields:

last_part='demo'
last_part='child'
last_part='terminal-slash'
last_part='query-params'
last_part='fragment'
last_part='all'
0
extracted_url = url[url.rfind("/")+1:];
0
0

Split the url and pop the last element url.split('/').pop()

0

Split the URL and pop the last element

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

-5
url ='http://www.test.com/page/TEST2'.split('/')[4]
print url

Output: TEST2.

1
  • 2
    You really should pass -1 as the index, otherwise this only works on strings with exactly that many / Sep 30, 2016 at 7:24

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.