Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Numpy char.capitalize() Function



The Numpy char.capitalize() function which is used to return a copy of each element in an array of strings with only the first character capitalized and all other characters lowercased.

This function applies the char method char.capitalize() element-wise to the input array which must be of type string or convertible to string.

This function is useful for uniformly formatting strings within NumPy arrays. It accepts a single argument, the input array and returns a new array of the same shape with capitalized string elements.

Syntax

Following is the syntax of Numpy char.capitalize() function −

numpy.char.capitalize(a)

Parameter

The Numpy char.capitalize() function accepts a single parameter namely, a, which is the input array with string to be capitalized.

Return Value

This function returns a copy of the input string with only the first character of each element capitalized.

Example 1

Following is the basic example of Numpy char.capitalize() function in which the first element of the given input string is capitalized and the rest of the elements changed to lower case −

import numpy as np
arr = np.array(['welcome', 'to', 'tutorialspoint'])
capitalized_arr = np.char.capitalize(arr)
print(capitalized_arr)

Below is the output of the basic example of numpy.char.capitalize() function −

['Welcome' 'To' 'Tutorialspoint']

Example 2

We can capitalize the first letter of each string in a NumPy array and converts the rest to lowercase by making it useful for normalizing strings with mixed cases. Below is the below example of it −

import numpy as np

arr = np.array(['hElLo', 'wOrLd'])
capitalized_arr = np.char.capitalize(arr)
print(capitalized_arr)

Here is the output of the above example −

['Hello' 'World']

Example 3

We have to note that when using the capitalize() function within each string, only the first character of the entire string is capitalized, not the first character of each word. Here in this example the first letter of each element of the array is capitalized while the rest of the characters remain in lowercase −

import numpy as np

arr = np.array(['hello world', 'good morning'])
capitalized_arr = np.char.capitalize(arr)
print(capitalized_arr)

Below is the output of capitalizeing an array with multiple words in each string −

['Hello world' 'Good morning']
numpy_string_functions.htm
Advertisements