【问题标题】:Remove leading and trailing slash / in python在python中删除前导和尾随斜杠/
【发布时间】:2012-05-11 15:17:00
【问题描述】:

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

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

我该怎么做?

【问题讨论】:

  • 为什么不想要前导斜杠?

标签: python django path strip


【解决方案1】:

你可以试试:

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

【讨论】:

  • 这对 9 年前已回答的已接受答案没有任何补充。
【解决方案2】:
def remove_lead_and_trail_slash(s):
    if s.startswith('/'):
        s = s[1:]
    if s.endswith('/'):
        s = s[:-1]
    return s

str.strip() 不同,这保证最多删除每侧的一个斜线。

【讨论】:

    【解决方案3】:

    另一个有正则表达式的:

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

    【讨论】:

      【解决方案4】:
      >>> "/get/category".strip("/")
      'get/category'
      

      strip() 是这样做的正确方法。

      【讨论】:

      • strip() 也会处理多个“/”
      • 还要注意 lstrip()rstrip() 的存在,以防你想例如删除尾部斜杠但保留前导斜杠。
      • 其实我觉得你应该用strip(os.sep)
      • 对于文件系统路径,os.path.normpath(*path*) 将去除尾部斜杠。
      • @EdwardFalk 如果服务器是 Windows 会中断。这里的上下文是 URL。
      猜你喜欢
      • 2012-06-06
      • 2011-02-20
      • 1970-01-01
      • 2018-07-28
      • 2012-01-17
      • 2016-04-21
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多