Remove leading and trailing slash / in python

PythonDjangoPathStrip

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

strip() is the proper way to do this.

Solution 2 - Python

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.

Solution 3 - Python

Another one with regular expressions:

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

Solution 4 - Python

you can try:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsumitView Question on Stackoverflow
Solution 1 - PythonAmberView Answer on Stackoverflow
Solution 2 - PythonRaymond HettingerView Answer on Stackoverflow
Solution 3 - PythonTim PietzckerView Answer on Stackoverflow
Solution 4 - PythonDev SapariyaView Answer on Stackoverflow