Python String strip() Method
Last Updated :
13 Nov, 2024
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)
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)
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)
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)
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.