STRING OPERATIONS IN NUMPY

In this tutorial, we are going to look at the numpy string operations and experiment with some of its methods by looking at some handy examples:




What are String Operations?

Strings in numpy is a module that allows us to perform operations on array which has a type of numpy.string or numpy.unicode_. All these operations are dependent on string methods in Python standard library.

We will be looking at some of the string methods to understand more about string operations:

numpy.char.add(x1,x2):

This method returns the sum of two arrays that has strings or unicode values. For example:

import numpy as np
a1 = np.array(("My name is "))
a2 = np.array(("hira"))
print(np.char.add(a1, a2))
 

Output:

My name is hira

numpy.char.multiply(a, i):

This method does the multiple concatenation of the element provided as ‘a’ with the number of times i.e. ‘i’, for example:

import numpy as np
a1 = np.array(("I love Numpy "))
print(np.char.multiply(a1, 5))

Output:

I love Numpy I love Numpy I love Numpy I love Numpy I love Numpy




numpy.char.capitalize(array):

This method capitalizes the array element-wise as well as a string, for example:

import numpy as np
a1 = np.array(["hello","i", "am", "numpy"])
print(np.char.capitalize(a1))

Output:

['Hello' 'I' 'Am' 'Numpy']

numpy.char.center():

Returns an array with the centered string element wise,, we make it possible by adding the number of characters that we want to center and add the fillchar as well for filling the right and left area, for example:

import numpy as np
print(np.char.center('pythontricks', 18, fillchar='*'))

String Operations in Numpy

Output:

***pythontricks***

To learn more about string operations, please refer to the official documentation of numpy