Remove leading and trailing slash / in python

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?

Asked By: sumit

||

Answers:

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

strip() is the proper way to do this.

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

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

Answered By: Raymond Hettinger

Another one with regular expressions:

>>> import re
>>> s = "/get/category"
>>> re.sub("^/|/$", "", s)
'get/category'
Answered By: Tim Pietzcker

You can try:

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

Answered By: Dev Sapariya
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.