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

Python String strip() Method

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

The strip() method removes leading and trailing whitespace characters from a string. We can also specify custom characters to remove.

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

Python
s = "  Hello Python!   "
res = s.strip()
print(res)

Output
Hello Python!

Syntax of strip() Method

s.strip(chars)

  • s: The input string
  • chars (optional): A set of characters to remove as leading/trailing characters

Examples of strip() Method

Remove leading and trailing whitespaces

Python
s = "   Hello Python!"
res = s.strip()
print(res)

Output
Hello Python!

Remove Custom Characters

If we have a string with various characters that we want to remove from both ends.

Python
s = '  ##*#Hello Python!#**##  '

# removes all occurrences of '#', '*', and ' ' 
# from start and end of the string
res = s.strip('#* ')
print(res)

Output
Hello Python!

Notes:

  • 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.

Remove Newline Characters

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

Python
s = '\nHello Python!\n'

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

print(res)

Output
Hello Python!

Related Articles:

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.


Previous Article
Next Article

Similar Reads

Article Tags :
Practice Tags :
three90RightbarBannerImg