Home  >  Article  >  Backend Development  >  The magical uses of strip() function in Python that you don’t know

The magical uses of strip() function in Python that you don’t know

Y2J
Y2JOriginal
2017-05-18 14:19:452623browse

[Appetizers]

When it comes to the strip method in python, everyone who has been exposed to python must know that it is mainly used to remove spaces. There are two ways to achieve this.

Method 1: Use the built-in function

if name == 'main' :
    str = ' Hello world '
    print '[%s]' %str.strip()

Method 2: Call the method in the string module

import string
if name == 'main' :
    str = ' Hello world '
    print '[%s]' %string.strip(str)

I don’t know if you are Any idea what the difference is between these two calls? The following are some personal opinions

Ø str.strip() is a built-in function that calls python, string.strip(str) is a method in the string module

Ø string.strip (str) is defined in the string module. And str.strip() is defined in the builtins module

Question 1: How to check whether a method in a module is defined in a built-in module?

Use dir (module name) to see if there is a 'builtins' attribute.

For example: View the string module

print dir(string)

Question 2. How to view all built-in functions in python

  print dir(sys.modules[ 'builtin' ])

Question 3. How to view the built-in modules Built-in function definition

 print help(builtins)

The above are all commonly known to everyone. Next, let’s get to the topic of this article:

[The hard dish]

First of all, please read it Take a look at the running results of the following program:

if name == 'main' :
    str = 'hello world'
    print str.strip( 'hello' )
    print str.strip( 'hello' ).strip()
    print str.strip( ' heldo ' ).strip()    #sentence 1
    stt = 'h1h1h2h3h4h'
    print stt.strip( 'h1' )                #sentence 2
    s = '123459947855aaaadgat134f8sfewewrf7787789879879'
    print s.strip( '0123456789' )         #sentence 3

The results are shown on the next page:

The running results:

world
world
wor
2h3h4
aaaadgat134f8sfewewrf

Did you answer it correctly? O(∩_∩)O~

If you got all the answers correct, I will give you 32 likes here...

Result analysis:

First, let’s check the string The strip source code in the module:

# Strip leading and trailing tabs and spaces
def strip (s, chars= None ):
    """strip(s [,chars]) -> string
    Return a copy of the string swith leading and trailing
    whitespace removed.
    If chars is given and not None,remove characters in chars instead.
    If chars is unicode, S will beconverted to unicode before stripping.
    """
return s.strip(chars)

I would like to take the liberty to translate it: This method is used to remove the leading and trailing spaces and tabs. Returns a copy of the S string with the spaces removed. If the parameter chars does not have a value of None, then all characters appearing in chars are removed. If chars is unicode, S is converted to unicode before operation.

The following is an explanation of sentence1 \2 \3 in the above paragraph:

str = 'hello world'
print str.strip( ' heldo ' ).strip()
result:wor
执行步骤:
elloworld
lloworld
oworld
oworl
 worl
 wor
wor

The specific code execution process:

  print str.strip( 'h' )
    print str.strip( 'h' ).strip( 'e' )
    print str.strip( 'h' ).strip( 'e' ).strip( 'l' )
    print str.strip( 'h' ).strip( 'e' ).strip( 'l' ).strip( 'd' )
    print str.strip( 'h' ).strip( 'e' ).strip( 'l' ).strip( 'd' ).strip( 'o' )
    print str.strip( 'h' ).strip( 'e' ).strip( 'l' ).strip( 'd' ).strip( 'o' ).strip( 'l' )
    print str.strip( 'h' ).strip( 'e' ).strip( 'l' ).strip( 'd' ).strip( 'o' ).strip( 'l' ).strip()

I don’t know if you understand the mystery. I discovered this rule with the help of project manager Shaan Fenyong.

Now to summarize a little:

s.strip(chars) usage rules:

First traverse the first character in chars to see if it is in S In the first and last position, if so, remove it. Set the removed new string to s and continue loop, starting from the first character in chars. If not, start directly from the second character of chars. Keep looping until the first and last characters in s are not in chars, then the loop terminates.

Key point: check whether the characters in chars are at the beginning and end of S

After reading this method, I found that the python source code developers are so awesome, they can even think of such a classic algorithm.

[After-dinner pastries]

This method is mainly used to remove specified characters at both ends according to specific rules. If sentence3 is a good application.

For example: intercept the numbers at both ends of the string, or get the string between the first and last occurrence of the characteristic character, etc.

【Related recommendations】

1. Python free video tutorial

2. The little-known traps of strip() in python

3. Basic introduction to python teaches you how to use the strip() function to remove spaces\n\r\t

4. Detailed explanation of python How to use strip() and split()

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

The above is the detailed content of The magical uses of strip() function in Python that you don’t know. 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