Python str.lstrip() function


str.lstrip() Function in Python

The str.lstrip() function in Python is used to remove leading (left-side) whitespace or specified characters from the beginning of a string. Unlike str.strip() which removes both leading and trailing characters, lstrip() only affects the left side of the string.

Syntax:

string.lstrip([chars])
  • string: The string you want to remove leading characters from.
  • chars (optional): A string specifying the set of characters to remove. If omitted, lstrip() will remove leading whitespace (spaces, tabs, newlines) by default.

Example 1: Removing leading whitespace

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

In this example:

  • The leading spaces before "Hello, Python!" are removed.
  • The rest of the string remains unchanged.

Example 2: Removing specific leading characters

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

Here:

  • The # characters at the beginning of the string are removed.
  • Characters in the middle of the string or the right side are not affected.

Example 3: Removing multiple specified characters

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

In this case:

  • The function removes all occurrences of $ from the left side of the string.
  • The ! characters and other content remain unaffected.

Key Points:

  • str.lstrip() removes leading (left-side) whitespace characters by default, such as spaces, tabs (\t), and newlines (\n).
  • You can specify which characters to remove by passing them as an argument.
  • Only the characters at the beginning (left side) of the string are removed.
  • It does not modify the original string but returns a new string with the modifications.

Example 4: Stripping leading newline characters

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

Here:

  • The leading newline characters (\n\n) are removed, but the rest of the string remains unchanged.