Remove leading and trailing slash / in python

◇◆丶佛笑我妖孽 提交于 2019-12-03 06:11:15

问题


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?


回答1:


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

strip() is the proper way to do this.




回答2:


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.




回答3:


Another one with regular expressions:

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


来源:https://stackoverflow.com/questions/10408826/remove-leading-and-trailing-slash-in-python

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