Remove leading and trailing slash / in python

2020-05-19 04:09发布

问题:

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:

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

strip() is the proper way to do this.



回答2:

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.



回答3:

Another one with regular expressions:

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