The Wayback Machine - https://web.archive.org/web/20241228170426/https://www.geeksforgeeks.org/python-string-strip/
Open In App

Python String strip() Method

Last Updated : 24 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

strip() method removes all leading and trailing whitespace characters from a string in Python. We can also customize it to strip specific characters by passing a string of characters to remove. It doesn’t modify the original string but returns a new one.

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:

  • The method removes spaces at the start and end of the string.
  • Inner spaces are not affected. This is useful for cleaning up user inputs or formatted text.

Syntax of strip() Method

s.strip(chars)

Parameters:

  • chars(optional)A string specifying the set of characters to remove from the beginning and end of the string.
  • If omitted, strip() removes all leading and trailing whitespace by default.

Return Type:

  • String: A new string with the specified characters (or whitespace) removed from both ends is returned.

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#**##  '

# removes all occurrences of '#', '*', and ' ' 
# from start and end of the string
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'

# Removing newline characters from both ends
res = s.strip()

print(res)

Output
Geeks for Geeks

Frequently Asked Questions (FAQs) on Python strip() Method

What characters does strip() remove by default?

By default, strip() removes whitespace characters, including spaces, tabs (\t), and newlines (\n).

Can strip() remove characters from the middle of a string?

No, strip() only removes characters from the beginning and end of a string. Characters in the middle of the string remain unaffected.

How is strip() different from replace()?

The strip() method is used for trimming characters from the ends of a string, while replace() can replace occurrences of a character or substring anywhere in the string.


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg