Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 559
sumit Avatar asked May 02 '12 06:05

sumit


People also ask

How do I get rid of trailing slashes in Python?

The most common approach is to use the . rstrip() string method which will remove all consecutive trailing slashes at the end of a string.

How do you remove leading in Python?

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.

How do I get rid of trailing slash?

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.


2 Answers

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

strip() is the proper way to do this.

like image 182
Amber Avatar answered Sep 22 '22 23:09

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.

like image 21
Raymond Hettinger Avatar answered Sep 22 '22 23:09

Raymond Hettinger