Python 3 – String lstrip() Method
In Python, the lstrip()
method is used to trim leading white spaces from a string. The method returns a new string after removing the white spaces at the beginning of the original string. The original string is not modified.
Syntax
The syntax for lstrip()
method is as follows:
string.lstrip([chars])
The lstrip()
method takes an optional parameter chars
. The chars
parameter specifies the set of characters to be removed from the left side of the string. If the chars
parameter is not specified, all whitespace characters such as space, tab, newline, etc. at the beginning of the string are removed.
Parameters
The lstrip()
method takes an optional parameter chars
. The chars
parameter specifies the set of characters to be removed from the left side of the string. If the chars
parameter is not specified, all whitespace characters such as space, tab, newline, etc. at the beginning of the string are removed.
Return Value
The lstrip()
method returns a new string after removing the specified characters from the left side of the string.
Examples
Here are a few examples that illustrate the use of the lstrip() method:
Example 1: Removing White Spaces
string = " Hello, World!"
print(string.lstrip())
Output:
"Hello, World!"
In the above example, we have used the lstrip()
method to remove leading white spaces from the given string. After removing leading white spaces, it will return the original string without leading white spaces.
Example 2: Removing Specified Characters
string = ",,,Hello, World!"
print(string.lstrip(','))
Output:
"Hello, World!"
In the above example, we have used the lstrip()
method to remove ,
character from the leading side of the string.
Example 3: Combining lstrip() Method with Other String Methods
string = " Hello, World! "
print(string.lstrip().upper())
Output:
"HELLO, WORLD! "
In the above example, we have used the lstrip()
method to remove leading white spaces from the given string, and then we have used the upper()
method to convert the string to all uppercase.
Conclusion
In conclusion, the lstrip()
method in Python 3 is a simple and efficient way to remove leading white spaces or specified characters from a string. With the help of this method, you can easily modify and manipulate strings according to your requirements.