Search code examples
pythonurlsplitdelimiter

How to split on a delimiter in python preserving the delimiter


so what i wanna do here is basically i have a file with a list of url endpoints, and i wanna split the links in the file on the slash delimter, basically generating sub-endpoints of endpoints, example:

https://www.somesite.com/path1/path2/path3

and i would want to get this:

https://www.somesite.com/path1/
https://www.somesite.com/path1/path2/
https://www.somesite.com/path1/path2/path3

i know how to achieve this in bash, but not with python, i tried using split function but it's very limited in my hands. i hope i can get some help here, thank you


Solution

  • One option is to split by a /, then slice the result and join back:

    >>> url = 'https://www.somesite.com/path1/path2/path3'
    >>> parts = url.split('/')
    >>> ['/'.join(parts[:p+1]) for p in range(3, len(parts))]
    ['https://www.somesite.com/path1', 'https://www.somesite.com/path1/path2', 'https://www.somesite.com/path1/path2/path3']