sumit
sumit

Reputation: 15464

Remove leading and trailing slash / in python

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?

Upvotes: 119

Views: 127485

Answers (3)

Raymond Hettinger
Raymond Hettinger

Reputation: 226181

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.

Upvotes: 19

Tim Pietzcker
Tim Pietzcker

Reputation: 336098

Another one with regular expressions:

>>> import re
>>> s = "/get/category"
>>> re.sub("^/|/$", "", s)
'get/category'

Upvotes: 8

Amber
Amber

Reputation: 526533

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

strip() is the proper way to do this.

Upvotes: 270

Related Questions