Python str.strip() function
str.strip()
Function in Python
The str.strip()
function in Python is used to remove leading (spaces before the string) and trailing (spaces after the string) whitespace characters from a string. It can also remove specific characters from both ends of the string if provided.
Syntax:
string
: The string you want to strip.chars
(optional): A string specifying the set of characters to remove. If omitted,strip()
will remove whitespace (spaces, tabs, newlines) by default.
Example 1: Removing whitespace
In this example:
- The leading and trailing spaces around
"Hello, Python!"
are removed. - The spaces between
"Hello,"
and"Python!"
are left unchanged becausestrip()
only affects the beginning and end of the string.
Example 2: Removing specific characters
Here:
- The
#
characters at both ends of the string are removed. strip()
only removes the characters from both ends and not from the middle.
Example 3: Removing multiple characters
In this case:
- The function removes all occurrences of
$
and!
from both ends of the string but does not affect the content within the string.
Key Points:
str.strip()
removes leading and trailing whitespace by default, including spaces, tabs (\t
), and newline characters (\n
).- You can pass a set of characters to remove from both ends of the string, and it will remove any occurrences of those characters.
- Only the edges of the string are affected, not the middle.
- The function returns a new string without modifying the original string.
Example 4: Stripping newline characters
Here:
- The newline characters (
\n
) at both ends of the string are removed, but the content in the middle is unchanged.