1. strip()
Strip (s[, chars]), which returns a copy of the string and removes the leading and suffix characters. means which characters you want to remove from the string, so you pass them in as arguments. This function only deletes the header and tail characters, not the middle ones. ) if the strip() parameter is empty, the blank character of the string header and tail (including \n, \r, \t, etc.) will be deleted by default.
#这里注意字符串a的两端都有一个空白字符,字符a和n之间也有一个。
a=" \rzha ng\n\t "
print(len(a))
b=a.strip()
print(b)
print(len(b))
输出:
11
zha ng
6
when the argument is empty, the whitespace, \r, \n, \t on both ends are deleted, but the whitespace in the middle stays the same. So let’s take a look at and what does look like when you have parameters:
a="rrbbrrddrr"
b=a.strip("r")
print(b)
输出:bbrrdd
, the middle character r has not changed, both ends have been deleted, now let’s look at passed in multiple character parameters :
a="aabcacb1111acbba"
print(a.strip("abc"))
print(a.strip("acb"))
print(a.strip("bac"))
print(a.strip("bca"))
print(a.strip("cab"))
print(a.strip("cba"))
输出:
1111
1111
1111
1111
1111
1111
, what do you see in this code?Contrary to what you might think, it doesn’t matter if you pass “ABC” or any other arrangement of ABC’s, what matters is that the function only knows that the characters you want to delete are “a”, “b”, “C”. The function takes the arguments you pass and breaks them down into characters, then removes the characters from the head and tail. Got it!
2. Lstrip () and rstrip()
these two functions are basically the same as the above strip(), and the parameter structure is the same, except that the left (head) is removed and the right (tail) is removed.
a=" zhangkang "
print(a.lstrip(),len(a.lstrip()))
print(a.rstrip(),len(a.rstrip()))
输出:
('zhangkang ', 10)
(' zhangkang', 10)
when there are no parameters, one gets rid of the white space on the left and one gets rid of the white space on the right. When passing parameters:
a="babacb111baccbb"
print(a.lstrip("abc"))
print(a.rstrip("abc"))
输出:
111baccbb
babacb111
div>