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.strip([chars])
  • 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

# Example 1: Removing leading and trailing whitespace my_string = " Hello, Python! " stripped_string = my_string.strip() print(stripped_string) # Output: "Hello, Python!"

In this example:

  • The leading and trailing spaces around "Hello, Python!" are removed.
  • The spaces between "Hello," and "Python!" are left unchanged because strip() only affects the beginning and end of the string.

Example 2: Removing specific characters

# Example 2: Removing specific characters my_string = "###Welcome###" stripped_string = my_string.strip("#") print(stripped_string) # Output: "Welcome"

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

# Example 3: Removing multiple specified characters my_string = "$$$Hello, Python!!!" stripped_string = my_string.strip("$!") print(stripped_string) # Output: "Hello, Python"

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

# Example 4: Removing newline characters my_string = "\nHello, Python!\n" stripped_string = my_string.strip() print(stripped_string) # Output: "Hello, Python!"

Here:

  • The newline characters (\n) at both ends of the string are removed, but the content in the middle is unchanged.