Remove leading and trailing slash /


Question

I am using request.path to return the current URL in Django, and it is returning /get/category.

I need it as get/category (without leading and trailing slash).

How can I do this?

1
51
1/9/2016 1:13:20 PM

Accepted Answer

>>> "/get/category".strip("/")
'get/category'

strip() is the proper way to do this.

138
5/2/2012 6:37:32 AM

def remove_lead_and_trail_slash(s):
    if s.startswith('/'):
        s = s[1:]
    if s.endswith('/'):
        s = s[:-1]
    return s

Unlink str.strip(), this is guaranteed to remove at most one of the slashes on each side.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon