Python string | strip() - GeeksforGeeks

文章推薦指數: 80 %
投票人數:10人

strip() is an inbuilt function in Python programming language that returns a copy of the string with both leading and trailing characters ... Skiptocontent CoursesGeekWeek2022ForWorkingProfessionalsDSAClasses(Live)SystemDesign(Live)JavaBackendDeveloper(Live)FullStack(Live)ExploreMoreLiveCoursesDSA(Self-Paced)SDETheory(Self-Paced)AllDevelopmentCourses(Self-Paced)ExploreMoreSelf-PacedCoursesForStudentsCompetitiveProgramming(Live)GATECourse2023(Live)DataScience(Live)ExploreMoreLiveCoursesDSA(Self-Paced)CIP(Self-Paced)JAVA/Python/C++(Self-Paced)ExploreMoreSelf-PacedCoursesSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#SQLScalaPerlGoLanguageKotlinWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesBusinessStudies(Class11th)BusinessStudies(Class12th)CSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersUPSCGeographyNotesHistoryNotesScience&Tech.NotesEthicsNotesPolityNotesEconomicsNotesUPSCPreviousYearPapersSSCCGLSSCCGLSyllabusGeneralStudiesEnglishReasoningSubjectwisePracticePapersPreviousYearPapersBankingExamsSBIClerkSBIClerkSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilitySBIClerkPracticePapersSBIPOSBIPOSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilityPreviousYearPapersSBIPOPracticePapersIBPSPOIBPSPO2022SyllabusEnglishNotesReasoningNotesPreviousYearPapersMockQuestionPapersIBPSClerkIBPSClerkSyllabusEnglishNotesPreviousYearPapersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests HomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesPythonStringrindex()MethodPythonStringrpartition()MethodPythonStringrsplit()MethodPythonStringrstrip()MethodPythonStringsplitlines()MethodPython|Stringstartswith()Pythonstring|strip()Pythonstring|swapcase()PythonStringTitlemethodPython|Stringtranslate()PythonStringupper()PythonString|zfill()PythonStringisupper()methodPythonStringjoin()MethodPythonStringlower()MethodPythonStringlstrip()methodPythonStringpartition()MethodPythonString|replace()PythonStringrfind()MethodPythonStringrindex()MethodPythonStringrpartition()MethodPythonStringrsplit()MethodPythonStringrstrip()MethodPythonStringsplitlines()MethodPython|Stringstartswith()Pythonstring|strip()Pythonstring|swapcase()PythonStringTitlemethodPython|Stringtranslate()PythonStringupper()PythonString|zfill()PythonStringisupper()methodPythonStringjoin()MethodPythonStringlower()MethodPythonStringlstrip()methodPythonStringpartition()MethodPythonString|replace()PythonStringrfind()MethodPythonstring|strip()ViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 11Aug,2021ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle strip()isaninbuiltfunctioninPythonprogramminglanguagethatreturnsacopyofthestringwithbothleadingandtrailingcharactersremoved(basedonthestringargumentpassed). Syntax: string.strip([chars]) Parameter: Thereisonlyoneoptionalparameterinit: 1)chars-astringspecifying thesetofcharacterstoberemoved. Iftheoptionalcharsparameterisnotgiven,allleading andtrailingwhitespacesareremovedfromthestring. ReturnValue: Returnsacopyofthestringwithbothleadingandtrailingcharactersremoved.Python3#Python3programtodemonstratetheuseof#strip()method  string="""   geeksforgeeks   """ #printsthestringwithoutstrippingprint(string) #printsthestringbyremovingleadingandtrailingwhitespacesprint(string.strip())   #printsthestringbyremovinggeeksprint(string.strip('geeks'))Output: geeksforgeeks geeksforgeeks for Python3#PythonProgramtodemonstrateuseofstrip()method str1='geeksforgeeks'#Printthestringwithoutstripping.print(str1) #Stringwhosesetofcharactersaretobe#removefromoriginalstringatbothitsends.str2='ekgs' #Printstringafterstrippingstr2fromstr1atbothitsend.print(str1.strip(str2))Output: geeksforgeeks for Workingofabovecode: Wefirstconstructastringstr1=‘geeksforgeeks’ Nowwecallstripmethodoverstr1andpassstr2=‘ekgs’asargument. Nowpythoninterpretertracestr1fromleft.Itremovethecharacterofstr1ifitispresentinstr2. Otherwiseitstopstracing. Nowpythoninterpretertracestr1fromright.Itremovethecharacterofstr1ifitispresentinstr2. Otherwiseitstoptracing. Nowatlastitreturnstheresultantstring.Whenwecallstrip()withoutargument,itremovesleadingandtrailingspaces.  Python3#PythonProgramtodemonstrateuseofstrip()methodwithoutanyargumentstr1="""   geeksforgeeks   """ #Printthestringwithoutstripping.print(str1) #Printstringafterremovingallleading#andtrailingwhitespaces.print(str1.strip())Input: geeksforgeeks Output: geeksforgeeksPracticalapplication: Givenastringremoveoccurrenceofword“the”fromthebeginningandtheend.  Python#Python3programtodemonstratethepracticalapplication#strip()  string="theKinghasthelargestarmyintheentireworldthe" #printsthestringafterremovingthefrombeginningandendprint(string.strip("the"))Input: theKinghasthelargestarmyintheentireworldthe Output: Kinghasthelargestarmyintheentireworld MyPersonalNotes arrow_drop_upSave LikePreviousPython|Stringstartswith()Next Pythonstring|swapcase()RecommendedArticlesPage:11,Jan1815,Jul1601,Sep2016,Jan1912,Sep1810,Apr2024,Nov2015,Mar2130,Oct1926,Nov1911,Dec1910,Feb2018,Feb2013,Jul2010,Jul2014,Aug2029,Aug2030,Aug1810,May1911,Nov1723,Nov1725,Mar2109,Nov2022,Nov19ArticleContributedBy:Striver@StriverVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:Vishalmastakkucoder123preetishneema312simranarora5sosgabaa406ArticleTags:python-stringPythonPracticeTags:pythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?