NumPy strings.capitalize()
The numpy.strings.capitalize()
function returns a copy of an input array of strings where only the first character of each element is capitalized. This operation is performed element-wise.
Syntax
</>
Copy
numpy.strings.capitalize(a)
Parameters
Parameter | Type | Description |
---|---|---|
a | array-like, with StringDType, bytes_, or str_ dtype | Input array of strings whose first character will be capitalized. |
Return Value
Returns an ndarray with the same dtype as the input, where each element has its first character capitalized and all other characters converted to lowercase.
Examples
1. Capitalizing a Single String
Here, we capitalize the first letter of a single string element inside an array.
</>
Copy
import numpy as np
# Define an array with a single string
word = np.array(['apple'])
# Capitalize the first letter
capitalized_word = np.strings.capitalize(word)
# Print the result
print("Original:", word)
print("Capitalized:", capitalized_word)
Output:
Original: ['apple']
Capitalized: ['Apple']

2. Capitalizing an Array of Strings
Capitalizing the first letter of multiple string elements in an array.
</>
Copy
import numpy as np
# Define an array of lowercase fruit names
fruits = np.array(['apple', 'banana', 'cherry'])
# Capitalize each element
capitalized_fruits = np.strings.capitalize(fruits)
# Print the results
print("Original:", fruits)
print("Capitalized:", capitalized_fruits)
Output:
Original: ['apple' 'banana' 'cherry']
Capitalized: ['Apple' 'Banana' 'Cherry']

3. Handling Mixed Case Strings
If the input strings have mixed case, the function ensures only the first letter is capitalized while the rest are converted to lowercase.
</>
Copy
import numpy as np
# Define an array with mixed case words
words = np.array(['aPPle', 'BANANA', 'cHeRrY'])
# Capitalize each element
capitalized_words = np.strings.capitalize(words)
# Print the results
print("Original:", words)
print("Capitalized:", capitalized_words)
Output:
Original: ['aPPle' 'BANANA' 'cHeRrY']
Capitalized: ['Apple' 'Banana' 'Cherry']

4. Capitalizing Byte Strings
Byte strings are also supported, and the operation is locale-dependent.
</>
Copy
import numpy as np
# Define an array of byte strings
byte_strings = np.array([b'apple', b'banana', b'cherry'], dtype='S')
# Capitalize each byte string
capitalized_bytes = np.strings.capitalize(byte_strings)
# Print the results
print("Original:", byte_strings)
print("Capitalized:", capitalized_bytes)
Output:
Original: [b'apple' b'banana' b'cherry']
Capitalized: [b'Apple' b'Banana' b'Cherry']
