The content of this article is to share with you some tips on how to use strip in Python. It has a certain reference value. Friends in need can refer to it
【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
#<python> if __name__ == '__main__': str = ' Hello world ' print '[%s]' %str.strip() #</python>
Method 2: Call the method in the string module
#<python> import string if __name__ == '__main__': str = ' Hello world ' print '[%s]' %string.strip(str) #</python>
I wonder if you know the difference 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 that calls the string module
Ø string.strip(str) It 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
#<python>print dir(string)#</python>
Question 2. How to view all built-in functions in python
#<python> print dir(sys.modules['__builtin__']) #</python>
Question 3, How to view the built-in function definitions in built-in modules
#<python>printhelp(__builtins__) #</python>
The above are all things that everyone usually knows. Let’s get into this article Topic:
[Hard Dish in Rice]
First of all, please take a look at the results of the following program:
#<python> 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 #</python>
The results are shown on the next page:
Run results:
world world wor 2h3h4 aaaadgat134f8sfewewrf
Did you answer correctly? O(∩_∩)O~
If you got all the answers correct, I will give you 32 likes here...
Result analysis:
First, let’s take a look at the strip source code in the string module:
#<python> # 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. """ returns.strip(chars) #</python>
Let’s take the liberty of translating it: This method is used to remove leading and trailing spaces and tabs. Returns a copy of the S string with 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:
#<python> str = 'hello world' print str.strip('heldo').strip() #</python> result:wor 执行步骤: elloworld lloworld oworld oworl worl wor wor
Specific code execution process:
#<python> 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') printstr.strip('h').strip('e').strip('l').strip('d').strip('o').strip('l').strip() #</python>
I don’t know if you understand the mystery. I discovered this rule with the help of project manager Shaan Fenyong.
Now a little summary:
s.strip(chars) usage rules:
First traverse the first character in chars to see if it is at the beginning and end of S , if so, remove it. Set the removed new string to s and continue looping, 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 developer is so awesome, even such a classic algorithm is thought of out.
[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.
The above is the detailed content of Tips on how to use strip in Python. For more information, please follow other related articles on the PHP Chinese website!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Mac version
God-level code editing software (SublimeText3)