NumPy capitalize() function

The capitalize() function is basically used to convert the first character of a string to an uppercase (capital) letter. If the string is having its first character as capital already, then this function will return the original string itself.

This function calls the str.capitalize in an element-wise manner.

This function is locale-dependent for an 8-bit string.

Syntax of capitalize():

The syntax required to use this function is as follows:

numpy.char.capitalize(arr)

The above syntax indicates that capitalize() function takes two parameters.

In the above syntax, the argument arr is mainly used to indicate the input array of the string on which this function will be applied.

Returned Values:

This function will return a string with the first character in the capital.

Example 1: With a string

The code snippet is as follows where we will use capitalize() function with a simple string:

import numpy as np 
 
a = "welcome to ShishirKant!!"
print("The original string:")
print(a)
print("Capitalizing the string using capitalize() function :")  

x = np.char.capitalize(a)
print(x)
The original string:
welcome to ShishirKant!!
Capitalizing the string using capitalize() function :
Welcome to shishirkant!!

Example 2:

Below we have a code snippet where we will use a string that is already capitalized as input then check the output for the same:

import numpy as np  

a = "ShishirKant is a best place to learn coding online"
print("The original string:\n")
print(a)
print("\n")
print("Capitalizing the string using capitalize() function:\n")  

x = np.char.capitalize(a)
print(x)
The original string:

ShishirKant is a best place to learn coding online

Capitalizing the string using capitalize() function:

Shishirkant is a best place to learn coding online

Example 3: With an array of strings

In this example we will take an array of strings and will use the capitalize() function with it:

import numpy as np

arr = np.array(['what aRE YOUR', 'plans for Tonight', 'will you','shishir kant']) 
print ("The original Input array : \n", arr) 

output = np.char.capitalize(arr)
print ("The output array: ", output)
The original Input array :
['what aRE YOUR' 'plans for Tonight' 'will you' 'shishir kant']
The output array: ['What are your' 'Plans for tonight' 'Will you' 'Shishir kant']

In the output, you should notice that not only this function changes the first character to uppercase in a string, but it also changes the other characters into lower case if they are in upper case, like it did for the string ‘what aRE YOUR‘ in the above example.

Follow Us On