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

</>
Copy
numpy.strings.lstrip(a, chars=None)

Parameters

ParameterTypeDescription
aarray-like, with StringDType, bytes_, or str_ dtypeThe input array containing strings.
charsscalar with the same dtype as a, optionalThe 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.

</>
Copy
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.

</>
Copy
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.

</>
Copy
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.

Additional Reading