Python provides the lstrip() method in order to return a copy of the string by removing the leading characters. The name lstrip comes from the “left strip“. This lstrip() method is very useful to remove spaces, tabs, etc from the specified string left side or from start of the string.
lstrip() Method Syntax
The lstrip() method has the following syntax.
- STRING is the string that is stripped left.
- CHARACTERS are the explicit characters we want to strip left from the specified STRING. CHARACTERS are optional and if not provided the spaces are stripped from the specified STRING.
The lstrip() method returns the stripped version of the STRING. So the returned value shluld be assigned into a variable if it will be used in the future.
Remove Spaces, Tabs From The Start Of The String
The lfsrip() method removes spaces and tabs by default if no characters are specified as parameter. The strip occurs in the left side of the string value. So the right side stays the same after the strip operation. Take a look to the following lstript() method examples and the results.
name=" ismail " print(name.lstrip()) name=" ismail" print(name.lstrip()) name="ismail " print(name.lstrip()) name=" ismail ".lstrip() print(name)
We see that the lstrip() method can be used with string literals without using a string variable.
Remove Specified Characters From Start Of The String
The lstrip() can be also used to remove specified characters from the left. The characters are provided as parameters to the string lstrip(). In the following example, we remove the characters “linux” from the string “linuxtect“.
site = "linuxtect" print(site.lstrip("linux"))
The output is like below.
Alternatively we can remove both spaces and some characters from the start of the string. In the following example we will remove ” AAA” which is first 3 spaces and 3 A’s.
site = " AAAlinuxtect" print(site.lstrip(" AAA"))