NumPy strings.lstrip()
The numpy.strings.lstrip()
function removes leading characters from each element of an input array.
By default, it removes whitespace, but a specific set of characters can also be defined.
Syntax
numpy.strings.lstrip(a, chars=None)
Parameters
Parameter | Type | Description |
---|---|---|
a | array-like, with StringDType , bytes_ , or str_ dtype | The input array containing strings. |
chars | scalar with the same dtype as a , optional | The set of characters to remove from the beginning of each string. If None, leading whitespace is removed. |
Return Value
Returns an array with the leading characters removed from each string element. The output dtype matches the input dtype.
Examples
1. Removing Leading Whitespace
In this example, we remove leading whitespace from an array of fruit names.
import numpy as np
# Define an array with leading spaces
fruits = np.array([" apple ", " banana ", " cherry", " mango"], dtype="str")
# Remove leading whitespace
result = np.strings.lstrip(fruits)
# Print the results
print("Original:", fruits)
print("After lstrip:", result)
Output:
Original: [' apple ' ' banana ' ' cherry' ' mango']
After lstrip: ['apple ' 'banana ' 'cherry' 'mango']

2. Removing Specific Leading Characters
We specify characters to be removed from the start of each string.
import numpy as np
# Define an array with unwanted leading characters
fruits = np.array(["xxapple", "yybanana", "zzcherry", "xxmango"], dtype="str")
# Remove specific leading characters ('x' and 'y' from each string)
result = np.strings.lstrip(fruits, chars="xy")
# Print the results
print("Original:", fruits)
print("After lstrip:", result)
Output:
Original: ['xxapple' 'yybanana' 'zzcherry' 'xxmango']
After lstrip: ['apple' 'banana' 'zzcherry' 'mango']

Here, 'x'
and 'y'
are removed from the beginning of the strings. However, 'z'
in “zzcherry” remains because it is not included in the specified chars
.
3. Using lstrip on a Mixed Character Set
This example demonstrates removing a mix of leading characters.
import numpy as np
# Define an array with multiple leading characters
fruits = np.array(["##apple", "**banana", "//cherry", "!!mango"], dtype="str")
# Remove specific characters from the start
result = np.strings.lstrip(fruits, chars="#*/!")
# Print the results
print("Original:", fruits)
print("After lstrip:", result)
Output:
Original: ['##apple' '**banana' '//cherry' '!!mango']
After lstrip: ['apple' 'banana' 'cherry' 'mango']

All defined characters (#, *, /, !
) are removed from the beginning of the strings.