Remove leading and trailing slash /

我是研究僧i 提交于 2019-12-02 18:41:54
>>> "/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

Unlink 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'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!