Home  >  Article  >  Backend Development  >  Little-known pitfalls of strip() in python

Little-known pitfalls of strip() in python

Y2J
Y2JOriginal
2017-05-18 14:29:582158browse

When using Python, I discovered a pitfall of the strip() command.

The previous understanding of strip(X) is: remove the "X" string contained at the beginning and end. If it is not included, it will not be removed.

One pitfall here is that python processes string X as a set, not as a fixed sequence of strings. In other words, X is treated as a set consisting of single letters. If the string being stripped() contains any character in the set on the left and right sides, it will be stripped(). Examples are as follows:

[python] view plain copy
 
>>> a="abc_1213"  
>>> a.strip('abc_')  
'1213'  
>>> a.strip('ba_c')  
'1213'  
>>> a.strip('zxcvbnmasdfghjklpoiuytrewq')  
'_1213'  
>>> a.strip('zxcvbnmasdfg_hjklpoiuytrewq')  
'1213'

At the beginning, my personal understanding is the first situation. After strip('abc_'), only the "abc_" on the left will be removed.

After the experiment, it was confirmed that the string to be stripped is treated as a set. As long as the characters on the left and right sides are in the set, they will be removed one by one until the first character not in the set is encountered.

【Related Recommendations】

1. Python free video tutorial

2. Basic introduction to python teaches you how to use strip() Function to remove spaces\n\r\t

3. Detailed explanation of how to use strip() and split() in python

4. Detailed explanation of the usage scenarios of strip function in python

5. The wonderful uses of strip() function in Python that you don’t know

The above is the detailed content of Little-known pitfalls of strip() in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn