为什么python str.strip方法没有删除此代码中的前导字符?

问题描述

我在下面使用了str.strip('0')。在下面的代码中,这不适用于前导零。

str1 = " 0000000this is string example....wow!!!0000000";
str1mod = str1.strip('0')
print str1mod
print len(str1mod)
str2 = "0000000this is string example....wow!!!0000000";
str2mod = str2.strip('0')
print str2mod
print len(str2mod)

输出类似于

 0000000this is string example....wow!!!
40
this is string example....wow!!!
32

为什么在 str1 中未删除前导空格?

期望是得到类似

输出
 this is string example....wow!!!
40
this is string example....wow!!!
32

解决方法

在您的情况下,零实际上不是“前导”,而是在其前面加一个空格,因此您要做的是将字符串剥离两次:

str1 = " 0000000this is string example....wow!!!0000000";
str1mod = str1.strip().strip('0')
print str1mod
print len(str1mod)
str2 = "0000000this is string example....wow!!!0000000";
str2mod = str2.strip('0')
print str2mod
print len(str2mod)

Python 2 shell中的输出:

Python 2.7.17 (default,Apr 15 2020,17:20:14) 
[GCC 7.5.0] on linux2
Type "help","copyright","credits" or "license" for more information.
>>> str1 = " 0000000this is string example....wow!!!0000000";
>>> str1mod = str1.strip().strip('0')
>>> print str1mod
this is string example....wow!!!
>>> print len(str1mod)
32
>>> str2 = "0000000this is string example....wow!!!0000000";
>>> str2mod = str2.strip('0')
>>> print str2mod
this is string example....wow!!!
>>> print len(str2mod)
32
>>> 
>>> 
,

str.strip([chars])

返回字符串删除前导和尾随字符的副本。 chars参数是一个字符串,指定要删除的字符集。如果省略或None,则chars参数默认为删除空格。

强调我的。

strip仅删除前导或尾随字符。由于0的序列不是前导的-它前面有一个空格-不会被剥离。

如果要从字符串的任何位置删除字符,请使用str.remove

如果您有更复杂的需求,请使用re.sub,例如删除开头和结尾的0,即使它们前面有空格,您也可以沿

re.sub(r'^(\s*)(0*)([^0]*)(0*)$',r'\1\3')