Remove leading and trailing slash / in python
Solution 1:
>>> "/get/category".strip("/")
'get/category'
strip()
is the proper way to do this.
Solution 2:
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:
Another one with regular expressions:
>>> import re
>>> s = "/get/category"
>>> re.sub("^/|/$", "", s)
'get/category'
Solution 4:
you can try:
"/get/category".strip("/")