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

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

Method 2: Call the method in the string module

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

print dir(string)
Copy after login

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

  print dir(sys.modules[ 'builtin' ])
Copy after login

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

 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:

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:

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:

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

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

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()
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 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
1664
14
PHP Tutorial
1268
29
C# Tutorial
1245
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.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles