Python String lstrip() Method



The Python String lstrip() method, as the name suggests, strips all the specified characters in a string from the beginning. That means, the method removes all combinations of the specified characters leading the string until a different character is found.

For instance, the characters "art" are to be stripped from the string "tarrasart", the resultant string we acquire will be "sart". The characters "tarra" are removed as "tar" and "ra" are both the combinations of "art". A different character 's' is encountered so the stripping is stopped.

If the specified characters to be stripped are not mentioned, the Python String lstrip() method will remove the leading whitespaces if there are any.

Syntax

Following is the syntax for Python String lstrip() method −

str.lstrip([chars])

Parameters

  • chars − You can supply what chars have to be trimmed.

Return Value

This method returns a copy of the string in which all chars have been stripped from the beginning of the string (default whitespace characters).

Example

If we create a string with unnecessary leading characters, the method will strip all the leading characters.

The following example shows the usage of Python String lstrip() method. Here, we are creating a string and passing a character to the method as an argument.

str = "88888888this is string example....wow!!!8888888";
print(str.lstrip('8'))

When we run above program, it produces following result −

this is string example....wow!!!8888888

Example

If no parameters are passed to the lstrip() method, the output will be returned as the original string with leading whitespaces removed.

In this example, we are inputting a string with leading whitespaces, say " this is string example....wow!!!". Passing a space parameter or no parameters to the lstrip() method when called will remove the leading whitespaces in the string created.

str = "      this is string example....wow!!!"
print(str.lstrip())
print(str.lstrip(' '))

When we run above program, it produces following result −

this is string example....wow!!!
this is string example....wow!!!

Example

If we pass a letter character for the input string, then only the leading case-based characters are stripped.

In the following example, we create a string that contains upper and lower case 'a' as leading characters and we will try to remove them using the lstrip() method. Since this method is case sensitive, only characters with same case are stripped.

str = "aaaaaAAAaaathis is string example"
print(str.lstrip('a'))

When we run above program, it produces following result −

AAAaaathis is string example
python_strings.htm
Advertisements