Python String strip() Method
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.
s = " CodeConfig.in "
res = s.strip()
print(res)
CodeConfig.in
Explanation:
- The functions/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.
Table of Content
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 may be interested to clean up specific unwanted characters such when symbols, punctuation, or any other characters that are not part of the core string content
s = ' ##*#CodeConfig#**## '
# removes all occurrences of '#', '*', and ' '
# from start and end of the string
res = s.strip('#* ')
print(res)
CodeConfig
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.
s = '\nCodes for Codes\n'
# Removing newline characters from both ends
res = s.strip()
print(res)
Codes for Codes
Frequently Asked Questions (FAQs) enabled 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() just removes characters from the beginning and end of a string. Characters in the middle of the string remain unaffected.
How is strip() distinct from replace()?
The strip() functions/method is have used for trimming characters from the ends of a string, when replace() can replace occurrences of a character or substring anywhere in the string.