Open In App

Python String strip() Method

Last Updated : 01 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

strip() method in Python removes all leading and trailing whitespace by default. You can also specify a set of characters to remove from both ends. It returns a new string and does not modify the original.

Let's take an example to remove whitespace from both ends of a string.

Python
s = "  GeeksforGeeks  "
res = s.strip()
print(res)

Output
GeeksforGeeks

Explanation: s.strip() removes spaces at the start and end of the string.

Syntax

s.strip(chars)

Parameters:

  • chars(optional): A string specifying the set of characters to remove from the beginning and end of the string.

Return Type: A new string with specified characters removed from both ends.

Examples of strip() Method

Removing Custom Characters

We can also use custom characters from the beginning and end of a string. This is useful when we want to clean up specific unwanted characters such as symbols, punctuation, or any other characters that are not part of the core string content

Python
s = '  ##*#GeeksforGeeks#**##  '

res = s.strip('#* ')
print(res)

Output
GeeksforGeeks

Explanation:

  • strip('#* ') removes any #, *, and spaces from both beginning and end of the string.
  • It stops stripping characters from both end once it encounters a character that are not in the specified set of characters.

Removing Newline Characters

We can also remove the leading and trailing newline characters (\n) from a string.

Python
s = '\nGeeks for Geeks\n'

res = s.strip()

print(res)

Output
Geeks for Geeks

Explanation: Removes newline characters \n from both ends of the string.

Strip Tabs and Spaces

Python
s = '\t  Hello World  \t'
res = s.strip()
print(res)

Output
Hello World

Explanation: Removes both tabs (\t) and spaces from the start and end of the string.

Related articles: newline characters (\n)


Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy