NumPy strings.partition()
The numpy.strings.partition()
function splits each element in an input array at the first occurrence of a specified separator.
It returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator.
Syntax
</>
Copy
numpy.strings.partition(a, sep)
Parameters
Parameter | Type | Description |
---|---|---|
a | array-like | Input array of strings. |
sep | array-like | Separator used to split each string element. |
Return Value
Returns a 3-tuple of arrays:
- The first array contains the part before the separator.
- The second array contains the separator itself.
- The third array contains the part after the separator.
Examples
1. Partitioning a Single String
Splitting the string “apple_pie” using the separator “_”.
</>
Copy
import numpy as np
# Define an array with a single string
arr = np.array(["apple_pie"])
# Partition the string using "_"
before, sep, after = np.strings.partition(arr, "_")
# Print the results
print("Before separator:", before)
print("Separator:", sep)
print("After separator:", after)
Output:
Before separator: ['apple']
Separator: ['_']
After separator: ['pie']

2. Partitioning an Array of Strings
Splitting multiple fruit names at the first occurrence of “a”.
</>
Copy
import numpy as np
# Define an array of fruit names
arr = np.array(["apple", "banana", "cherry", "grape"])
# Partition the strings using "a"
before, sep, after = np.strings.partition(arr, "a")
# Print the results
print("Before separator:", before)
print("Separator:", sep)
print("After separator:", after)
Output:
Before separator: ['' 'b' 'cherry' 'gr']
Separator: ['a' 'a' '' 'a']
After separator: ['pple' 'nana' '' 'pe']

3. Partitioning When the Separator is Not Found
If the separator is not found in a string, the entire string is placed in the first part, and the second and third parts are empty.
</>
Copy
import numpy as np
# Define an array with a word that doesn't contain the separator
arr = np.array(["cherry"])
# Partition using "_"
before, sep, after = np.strings.partition(arr, "_")
# Print the results
print("Before separator:", before)
print("Separator:", sep)
print("After separator:", after)
Output:
Before separator: ['cherry']
Separator: ['']
After separator: ['']

4. Partitioning Using a Different Separator
Using a different separator to split strings.
</>
Copy
import numpy as np
# Define an array of strings
arr = np.array(["apple-banana", "cherry-mango", "grape-orange"])
# Partition the strings using "-"
before, sep, after = np.strings.partition(arr, "-")
# Print the results
print("Before separator:", before)
print("Separator:", sep)
print("After separator:", after)
Output:
Before separator: ['apple' 'cherry' 'grape']
Separator: ['-' '-' '-']
After separator: ['banana' 'mango' 'orange']

In this case, the separator "-"
successfully splits each string into three parts.