strip()与lstrip()和rstrip()在Python中的区别

8
我尝试使用 rstrip()lstrip(),像这样:
>>> a = 'thisthat'
>>> a.lstrip('this')
'at'
>>> a.rstrip('hat')
'this'
>>> a.rstrip('cat')
'thisth'

这些方法到底在做什么?对于第一个情况,我期望返回 'thist',而对于第二个情况,我期望返回 'that'。
我并不想修复问题,只是想理解其功能。
如果你想解决从字符串的开头或结尾删除内容的问题(或者是试图关闭类似的重复问题),请参考如何从字符串的末尾删除子字符串?

1
要了解strip及其一些示例用途,我建议看一下以下链接https://www.dotnetperls.com/strip-python - Manohar Swamynathan
5个回答

13

文档中可以得知:

str.strip([chars])
返回一个将字符串首尾指定字符删除后的字符串副本。参数 chars 是用于指定需要删除的字符集合的字符串。如果省略或设置为 None,则默认删除空白字符。参数 chars 并不是前缀或后缀;而是删除所有它的值组合:

因此,strip 会尝试将 chars 参数中列出的任何字符从两端删除,只要可能就会一直删除。也就是说,提供给函数作为参数的字符串被视为字符集合,而不是子字符串。

lstriprstrip 的工作方式相同,只是 lstrip 只在左侧(开头)删除字符,而 rstrip 只在右侧(结尾)删除字符。


3
a = 'thisthat'    
a.rstrip('hat')

等同于

a = 'thisthat' 
to_strip = 'hat'
while a[-1] in to_strip:
    a = a[:-1]

切片操作符的结尾不包括在内,因此应该写成a = a[:-1]。 - Vélimir

1
strip()可以从字符串的左右两侧移除所有特定字符的组合(默认为空格)。 lstrip()可以从字符串的左侧移除所有特定字符的组合(默认为空格)。 rstrip()可以从字符串的右侧移除所有特定字符的组合(默认为空格)。
test = "    a b c    "

print(test)          # "    a b c    "
print(test.strip())  # "a b c"
print(test.lstrip()) # "a b c    "
print(test.rstrip()) # "    a b c"

test = "abc a b c abc"

print(test)               # "abc a b c abc"
print(test.strip("cab"))  # " a b c "
print(test.lstrip("cab")) # " a b c abc"
print(test.rstrip("cab")) # "abc a b c "

test = "abc a b c abc"

print(test)               # "abc a b c abc"
print(test.strip("c ab"))  # ""
print(test.lstrip("c ab")) # ""
print(test.rstrip("c ab")) # ""

-1
这是我对 lstriprstrip 方法的理解:
#USING RSTRIP
a = 'thisthat'
print(a.rstrip('hat'))
#Begin with t on the right side, is t in 'hat'? Okay, remove it
#Next: a, is a in 'hat'? Okay remove it
#Next: h, is h in 'hat'? Okay, remove it
#Next: t, is t in 'hat'? Okay, remove it
#Next: s, is s in 'hat'? No, so, stop.
#Output: this

#USING LSTRIP
b = 'thisthat'
print(b.lstrip('this')) 
#Begin with t on the left side, is t in 'this'? Okay, remove it
#Next: h, is h in 'this'? Okay, remove it
#Next: i, is i in 'this'? Okay,  remove it
#Next: s, is s in 'this'? Okay, remove it
#Next: t, is t in 'this'? Okay, remove it
#Next: h, is h in 'this'? Okay, remove it
#Next: a, is a in 'this'? No, so, stop
#Ouput: at

#Using STRIP
c = 'thisthat'
print(c.strip("th"))
#Begin from both sides and repeat the steps from above; essentially, stripping from both sides.
#Using lstrip => isthat
#Now, using rstrip => istha
#Ouput: istha

-1

lstriprstripstrip 分别从字符串的左侧、右侧和两端删除字符。默认情况下,它们会删除空格字符(空格、制表符、换行符等)。

>>> a = '  string with spaces  '
>>> a.strip()
'string with spaces'
>>> a.lstrip()
'string with spaces  '
>>> a.rstrip()
'  string with spaces'

你可以使用chars参数来改变它去除的字符。
>>> a = '....string....'
>>> a.strip('.')
'string'

然而,根据你的问题,听起来你实际上是在寻找替换功能

>>> a = 'thisthat'
>>> a.replace('hat', '')
'thist'
>>> a.replace('this', '')
'that'

@B Rad C 不,我不是在寻找替换,我以为当我从字符串中剥离一个单词时,它会取该子字符串并将其剥离。我不知道它会尽可能地取字符,就像Ahsanul Haque所解释的那样。 - sans0909

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接