search
HomeBackend DevelopmentPython TutorialTips on how to use strip in Python

Tips on how to use strip in Python

Apr 09, 2018 pm 03:25 PM
pythonstripInstructions

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__ == &#39;__main__&#39;:
    str = &#39; Hello world &#39;
    print &#39;[%s]&#39; %str.strip()
#</python>

Method 2: Call the method in the string module

#<python>
import string
if __name__ == &#39;__main__&#39;:
    str = &#39; Hello world &#39;
    print &#39;[%s]&#39; %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[&#39;__builtin__&#39;])
 #</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__ == &#39;__main__&#39;:
    str = &#39;hello world&#39; 
    print str.strip(&#39;hello&#39;)
    print str.strip(&#39;hello&#39;).strip()
    print str.strip(&#39;heldo&#39;).strip()   #sentence 1
   
    stt = &#39;h1h1h2h3h4h&#39;
    print stt.strip(&#39;h1&#39;)               #sentence 2
   
    s =&#39;123459947855aaaadgat134f8sfewewrf7787789879879&#39;
    print s.strip(&#39;0123456789&#39;)        #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 = &#39;hello world&#39;
print str.strip(&#39;heldo&#39;).strip()
#</python>
result:wor
执行步骤:
elloworld
lloworld
oworld
oworl
 worl
 wor
wor

Specific code execution process:

#<python>
    print str.strip(&#39;h&#39;)
    print str.strip(&#39;h&#39;).strip(&#39;e&#39;)
    print str.strip(&#39;h&#39;).strip(&#39;e&#39;).strip(&#39;l&#39;)
    print str.strip(&#39;h&#39;).strip(&#39;e&#39;).strip(&#39;l&#39;).strip(&#39;d&#39;)
    print str.strip(&#39;h&#39;).strip(&#39;e&#39;).strip(&#39;l&#39;).strip(&#39;d&#39;).strip(&#39;o&#39;)
    print str.strip(&#39;h&#39;).strip(&#39;e&#39;).strip(&#39;l&#39;).strip(&#39;d&#39;).strip(&#39;o&#39;).strip(&#39;l&#39;)
    printstr.strip(&#39;h&#39;).strip(&#39;e&#39;).strip(&#39;l&#39;).strip(&#39;d&#39;).strip(&#39;o&#39;).strip(&#39;l&#39;).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!

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
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor