Python 字符串条函数



为什么下面的代码可以删除'+':

a = '+'
a.strip('+')
#output: ''
a = '1+'
a.strip('+')
#output: '1'
a = '+66'
a.strip('+')
#output: '66'

但以下不能:

a = '1+2'
a.strip('+')
#output: '1+2'

为什么?

strip() 函数仅删除字符串外部的前导和尾随字符。由于在上一个示例中,+位于中间,因此不会将其删除。也许尝试改用replace()

my_str = "1+2"
new_str = my_str.replace("+", "")

strip只删除字符串中的指定标题和尾随字符,而不是中间。

同样,rstrip仅删除尾随的。

相关内容

最新更新