【问题标题】:How is lstrip() method removing chars from left? [duplicate]lstrip() 方法如何从左侧删除字符? [复制]
【发布时间】:2021-12-07 22:28:53
【问题描述】:

我的理解是lstrip(arg)根据arg的值从左边删除字符。

我正在执行以下代码:

'htp://www.abc.com'.lstrip('/')

输出:

'htp://www.abc.com'

我的理解是所有字符都应该从左边去掉,直到达到/。 换句话说,输出应该是:

'www.abc.com'

我也不确定为什么运行以下代码会生成以下输出:

'htp://www.abc.com'.lstrip('/:pth')

输出:

'www.abc.com'

【问题讨论】:

  • lstip() 从左边去掉所有指定的字符。试试//////htp://www.abc.comdoc

标签: python python-3.x string strip


【解决方案1】:

调用help 函数显示如下:

Help on built-in function lstrip:

lstrip(chars=None, /) method of builtins.str instance
    Return a copy of the string with leading whitespace removed.
    
    If chars is given and not None, remove characters in chars instead.

这显然意味着开头(即左侧)中的任何空格都将被切掉,或者如果指定了 chars 参数,它将删除这些字符当且仅当字符串以任何指定的开头字符,即如果您将'abc' 作为参数传递,则字符串应以'a''b''c' 中的任何一个开头,否则该函数不会更改任何内容。 整个字符串不必以'abc' 开头。

print(' the left strip'.lstrip())    # strips off the whitespace
the left strip
>>> print('ththe left strip'.lstrip('th'))    # strips off the given characters as the string starts with those
e left strip
>>> print('ththe left strip'.lstrip('left'))    # removes 't' as 'left' contatins 't' in it
hthe left strip
>>> print('ththe left strip'.lstrip('zeb'))    # doesn't change anything as the argument passed doesn't match the beggining of the string
ththe left strip
>>> print('ththe left strip'.lstrip('h'))    # doesn't change anything as the argument passed doesn't match the beggining of the string
ththe left strip

【讨论】:

    【解决方案2】:

    如果您希望给定字符串的所有字符都正确,请尝试拆分

    url = 'htp://www.abc.com'
    print(url.split('//')[1])
    

    输出

    www.abc.com
    

    lstrip 只返回去掉前导字符的字符串副本,而不是介于两者之间

    【讨论】:

    • 你能帮我理解'htp://www.abc.com'.lstrip('/:pth')的输出吗?我刚刚更新了我的问题
    • @meallhour strip()'/:pth' 视为要删除的字符,而不是要删除的前缀。所以字符的顺序没有可见的效果。
    【解决方案3】:

    我想你想要这个:

    a = 'htp://www.abc.com'
    a = a[a.find('/')+1:]
    

    来自 Python 文档: str.lstrip([chars])

    Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. **The chars argument is not a prefix; rather, all combinations of its values are stripped:**
    

    阅读最后一行,您的疑问将得到解决。

    【讨论】:

      【解决方案4】:

      在 Python documentation 中,str.lstrip 只能删除其 args 中指定的前导字符,如果没有提供任何字符,则可以删除空格。

      您可以尝试像这样使用str.rfind

      >>> url = "https://www.google.com"
      >>> url[url.rfind('/')+1:]
      'www.google.com'
      

      【讨论】: