Home Backend Development Python Tutorial 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

May 18, 2017 pm 02:19 PM
python strip

[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

1

2

3

if name == 'main' :

    str = ' Hello world '

    print '[%s]' %str.strip()

Copy after login

Method 2: Call the method in the string module

1

2

3

4

import string

if name == 'main' :

    str = ' Hello world '

    print '[%s]' %string.strip(str)

Copy after login

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

1

print dir(string)

Copy after login

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

1

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

Copy after login

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

1

print help(builtins)

Copy after login

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:

1

2

3

4

5

6

7

8

9

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

Copy after login

The results are shown on the next page:

The running results:

1

2

3

4

5

world

world

wor

2h3h4

aaaadgat134f8sfewewrf

Copy after login

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:

1

2

3

4

5

6

7

8

9

# 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)

Copy after login

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:

1

2

str = 'hello world'

print str.strip( ' heldo ' ).strip()

Copy after login

1

2

3

4

5

6

7

8

9

result:wor

执行步骤:

elloworld

lloworld

oworld

oworl

 worl

 wor

wor

Copy after login

The specific code execution process:

1

2

3

4

5

6

7

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()

Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1280
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles