方法strip不能从我的字符串中删除字符

问题描述

>>> y = 'This is string,should be without commas,but is not working'
>>> y = x.strip(",")
>>> y
'This is string,but is not working'

我想从此字符串中删除逗号,但是如上所示,strip方法不起作用。

解决方法

strip()函数仅删除开头和结尾字符。而且因为您给它加上了逗号作为参数,所以它只会删除前导和尾随逗号。

要从字符串中删除所有逗号,可以使用replace()函数。因此,您的第二行将变为:

y = x.replace(",","")
,

strip()方法通过删除开头和结尾字符(基于传递的字符串参数)来返回字符串的副本。例如,在您的工作案例strip()上可以使用类似的方法:

y = ',This is string,should be without commas,but is not working,'
x = y.strip(',')
print(x)
This is string,but is not working

这将为您提供所需的东西:

y = 'This is string,but is not working'
x = y.replace(',','')

哪个输出:

print(x)
This is string should be without commas but is not working