Python string | strip() - GeeksforGeeks
文章推薦指數: 80 %
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
延伸文章資訊
- 1Python String strip() - Programiz
The strip() method removes characters from both left and right based on the argument (a string sp...
- 2Python strip()方法 - 菜鸟教程
Python strip()方法Python 字符串描述Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。 注意:该方法只能删除开头或是结尾的字符 ...
- 3Python String strip() Method - W3Schools
Python String strip() Method · Example. Remove spaces at the beginning and at the end of the stri...
- 4Python strip()方法- Python教學 - 極客書
strip()方法返回所有字符從開始及字符串的末尾(默認空格字符)被去除後的字符串的一個副本。 語法以下是strip()方法的語法: str . strip ([ chars ]) ...
- 5Python string | strip() - GeeksforGeeks
strip() is an inbuilt function in Python programming language that returns a copy of the string w...