109

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?

sumit
  • 15,003
  • 12
  • 69
  • 110

3 Answers3

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

strip() is the proper way to do this.

Amber
  • 507,862
  • 82
  • 626
  • 550
18
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.

Alex Tartan
  • 6,736
  • 10
  • 34
  • 45
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
8

Another one with regular expressions:

>>> import re
>>> s = "/get/category"
>>> re.sub("^/|/$", "", s)
'get/category'
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561