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?
The most common approach is to use the . rstrip() string method which will remove all consecutive trailing slashes at the end of a string.
Python Strip Characters: lstrip() and rstrip() The Python lstrip() method removes the leading spaces—or A leading character you specified— from the left side of a string. The rstrip() method removes trailing spaces or characters from the right side of a string.
Use the String. replace() method to remove a trailing slash from a string, e.g. str. replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.
>>> "/get/category".strip("/") 'get/category'
strip()
is the proper way to do this.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With