strip在python中是如何工作的?

2024-10-03 02:34:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道rstrip和lstrip在python中是如何工作的。 如果我有一根绳子

>> a = 'thisthat'
>> a.rstrip('hat')
out : 'this'
>> a.lstrip('this')
out: 'at'
>> a.rstrip('cat')
out: 'thisth'

如何删除一个单词?在

理想的输出应该是“thist”(第一种情况)和“that”(第二种情况)对吗?在

还是像正则表达式一样,匹配每个字符,以及它在末尾看到的字符(对于第三种情况)?在

注意:我不是在寻找replace,我只想知道strip如何工作,同时从字符串中剥离子字符串。在


Tags: 字符串hat情况outthis字符单词at
3条回答
a = 'thisthat'    
a.rstrip('hat')

等于

^{pr2}$

doc

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

strip接受一个字符参数,并将尽可能长时间地从两端删除这些字符。在

参数被视为一组字符,而不是子串。在

lstriprstrip的工作方式完全相同,只是其中一个只从左侧剥离,另一个从右侧剥离。在

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

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

您可以使用chars参数更改它删除的字符。在

^{pr2}$

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

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

相关问题 更多 >