删除 Python 中的前斜杠和后斜杠

我使用 request.path返回 Django 中的当前 URL,它返回的是 /get/category

我需要它作为 get/category(没有前导和尾随斜杠)。

我怎么能这么做?

102614 次浏览
>>> "/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.

Another one with regular expressions:

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

You can try:

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