【问题标题】:Why does str.lstrip strip an extra character? [duplicate]为什么 str.lstrip 会去除多余的字符? [复制]
【发布时间】:2010-12-13 19:36:20
【问题描述】:
>>> path = "/Volumes/Users"
>>> path.lstrip('/Volume')
's/Users'
>>> path.lstrip('/Volumes')
'Users'
>>> 

我希望path.lstrip('/Volumes') 的输出是'/Users'

【问题讨论】:

    标签: python string


    【解决方案1】:

    lstrip 是基于字符的,它从左端删除该字符串中的所有字符。

    要验证这一点,试试这个:

    "/Volumes/Users".lstrip("semuloV/")  # also returns "Users"
    

    由于/ 是字符串的一部分,因此将其删除。

    您需要改用切片:

    if s.startswith("/Volumes"):
        s = s[8:]
    

    或者,在 Python 3.9+ 上,您可以使用 removeprefix

    s = s.removeprefix("/Volumes")
    

    【讨论】:

    • 这是“一种显而易见的方法”。
    • 要更有效地删除前缀,请使用 split,maxsplits=1 path = "/Volumes/Users" drive = "/Volumes" if path.startswith(drive): path = path.split(drive, 1)[1]
    【解决方案2】:

    Strip 是基于字符的。如果您正在尝试进行路径操作,您应该查看os.path

    >>> os.path.split("/Volumes/Users")
    ('/Volumes', 'Users')
    

    【讨论】:

    • 现在,使用pathlib 代替:from pathlib import Path 然后Path("/Volumes/Users").namePath("/Volumes/Users").parts[-1]
    【解决方案3】:

    传递给lstrip 的参数被视为一组字符!

    >>> '   spacious   '.lstrip()
    'spacious   '
    >>> 'www.example.com'.lstrip('cmowz.')
    'example.com'
    

    另请参阅documentation

    你可能想使用 str.replace()

    str.replace(old, new[, count])
    # e.g.
    '/Volumes/Home'.replace('/Volumes', '' ,1)
    

    返回字符串的副本,其中所有出现的子字符串 old 都替换为 new。如果给出了可选参数 count,则仅替换第一个 count 出现。

    对于路径,您可能需要使用os.path.split()。它返回路径元素的列表。

    >>> os.path.split('/home/user')
    ('/home', '/user')
    

    你的问题:

    >>> path = "/vol/volume"
    >>> path.lstrip('/vol')
    'ume'
    

    上面的例子展示了lstrip() 的工作原理。它删除了左侧的“/vol”起始形式。然后,又开始了…… 因此,在您的示例中,它完全删除了“/Volumes”并开始删除“/”。它只删除了“/”,因为这个斜线后面没有“V”。

    HTH

    【讨论】:

    • '/home/user/Volumes/important_path'.replace('/Volumes', '', 1) --> '/home/user/important_path'
    • '/home/user/Volumes_for_my_mp3s/jazz'.replace('/Volumes', '', 1) --> '/home/user_for_my_mp3s/jazz'。看看你还缺少什么? :)
    • 是的。我知道... str.replace 只是 Vijayendra Bapte 的这个特定示例的一个示例。
    • 如果不适用于一般情况,那就这么说吧:也许他的例子只是他需要的一百个例子中的一个继续运行。
    • @Mark:我写道:'返回字符串的副本,其中所有出现的子字符串 old 都替换为 new。如果给出了可选参数计数,则仅替换第一次出现的计数。'
    【解决方案4】:

    lstrip 文档说:

    Return a copy of the string S with leading whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    If chars is unicode, S will be converted to unicode before stripping
    

    因此,您将删除给定字符串中包含的每个字符,包括“s”和“/”字符。

    【讨论】:

      【解决方案5】:

      这是一个原始版本的 lstrip(我写的),它可能会帮助你理清思路:

      def lstrip(s, chars):
          for i in range len(s):
              char = s[i]
              if not char in chars:
                  return s[i:]
              else:
                  return lstrip(s[i:], chars)
      

      因此,您可以看到每次出现在 chars 中的字符都被删除,直到遇到不在 chars 中的字符。一旦发生这种情况,删除就会停止,字符串的其余部分会被简单地返回

      【讨论】:

        猜你喜欢
        • 2019-06-01
        • 1970-01-01
        • 2021-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-14
        • 2020-12-01
        相关资源
        最近更新 更多