String strip() Method in Python

Python String strip() Method

In Python, the strip() method is a built-in string method used to remove leading and trailing whitespace characters from a string. Whitespace characters include spaces, tabs, newlines, and any other characters that are considered as white space in Python.

The syntax for the strip() method is:

string.strip(characters)

Here:

  • string: The original string from which you want to remove leading and trailing whitespace characters.
  • characters (optional): An optional parameter that specifies the characters you want to remove from the beginning and end of the string. If not provided, the method will remove all whitespace characters.

The strip() method does not modify the original string; instead, it returns a new string with the leading and trailing whitespace removed.

Let's see some examples:

Basic usage:

text = "   Hello, world!   "
result = text.strip()
print(result)  # Output: "Hello, world!"

Stripping specific characters:

text = "###+++---Hello, world!---+++###"
result = text.strip("#+-")
print(result)  # Output: "Hello, world!"

Removing newlines:

multiline_text = "\n\nThis is a multiline text.\n\n\n"
result = multiline_text.strip()
print(result)  # Output: "This is a multiline text."

It's important to note that the strip() method only removes leading and trailing characters; it does not remove characters within the string. If you want to remove specific characters inside the string, you can use other string methods like replace() or regular expressions.