strip() method removes specified characters from both the beginning and the end of a string. If no characters are provided, it removes leading and trailing whitespace by default.
text = " Python Programming "
res = text.strip()
print(res)
Output
Python Programming
Explanation: s.strip() removes spaces at the start and end of the string.
Syntax
string.strip(chars)
- Parameters: chars (optional) - Specifies the characters to remove from the beginning and end of the string. If omitted, whitespace characters are removed.
- Return Type: A new string with the specified characters removed from both ends. The original string remains unchanged.
Removing Specific Characters
strip() method can remove a specified set of characters from both ends of a string. This is useful for cleaning symbols, punctuation marks, or other unwanted characters.
text = "##@@Python@@##"
res = text.strip("#@")
print(res)
Output
Python
Explanation: strip("#@") removes all # and @ characters from both ends. Characters inside the string are not affected.
Removing Newline Characters
Text read from files or user input often contains newline characters (\n). The strip() method can remove them from both ends of a string.
text = "\nPython Programming\n"
res= text.strip()
print(res)
Output
Python Programming
Explanation: strip() removes leading and trailing newline characters. It also removes any surrounding whitespace characters by default.
Removing Tabs and Spaces
Strings may contain extra spaces or tab characters that need to be cleaned before processing.
text = "\t Hello World \t"
res = text.strip()
print(res)
Output
Hello World
Explanation: strip() removes tabs (\t) and spaces from both ends. The text between words remains unchanged.