python3 strip lstrip rstrip delete the specified character string from beginning to end

1. strip()

Its function prototype: string.strip (s [, chars]), which returns a string copy, and delete the leading and trailing characters. (Which means that you want to remove the character in the string, and then you put these characters as parameter. This function only deletes the character head and tail, the middle will not be deleted.) If the parameter strip () is empty then delete the default string head and tail of white space characters (including \ n, \ r, \ t these).

#这里注意字符串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 parameter is empty, both ends of the whitespace, \ r, \ n, \ t have been deleted, but the middle whitespace that did not move. We look at when the time parameters have what the situation is:
a="rrbbrrddrr"
b=a.strip("r")
print(b)

输出:bbrrdd
R the middle of the character did not move, the two ends are deleted, and now look at us pass more than one character parameters situations:
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 you see from this code? And you might think differently when you pass parameters either "abc" abc or other forms of arrangement, this is not important, it is important to know the function you want to delete a character is "a", "b", "c". You will pass the function parameters broken down into a number of characters, then the head and tail of these characters removed. you got it!

2. lstrip () and rstrip () 

These two functions of the above strip () is basically the same, the same parameter structure, only one is removed on the left (the head), a right is removed (tail).

a=" zhangkang "
print(a.lstrip(),len(a.lstrip()))
print(a.rstrip(),len(a.rstrip()))

输出:
('zhangkang ', 10)
(' zhangkang', 10)

When there is no argument, removes a blank left a blank space on the right removed. When the transmission parameters:

a="babacb111baccbb"
print(a.lstrip("abc"))
print(a.rstrip("abc"))

输出:
111baccbb
babacb111

 

 

Published 57 original articles · won praise 538 · Views 4.86 million +

Guess you like

Origin blog.csdn.net/whatday/article/details/104055981