Python字符串条功能

时间:2017-03-25 18:18:09

标签: 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'

为什么?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

同样,rstrip仅删除尾随的那些。