w3resource

NumPy: Split the element of a given array with spaces

NumPy String: Exercise-10 with Solution

Write a NumPy program to split the element of a given array with spaces.

Sample Solution:

Python Code:

# Importing necessary library
import numpy as np

# Creating a NumPy array containing a single string
x = np.array(['Python PHP Java C++'], dtype=np.str)

# Displaying the original array
print("Original Array:")
print(x)

# Splitting the single string in the array based on spaces
r = np.char.split(x)

# Displaying the result after splitting the string
print("\nSplit the element of the said array with spaces: ")
print(r) 

Sample Input:

(['Python PHP Java C++'], dtype=np.str)

Sample Output:

Original Array:
['Python PHP Java C++']

Split the element of the said array with spaces: 
[list(['Python', 'PHP', 'Java', 'C++'])]

Explanation:

In the above exercise –

x = np.array(['Python PHP Java C++'], dtype=np.str): This code creates a 1-dimensional numpy array x of strings containing only one element "Python PHP Java C++".

r = np.char.split(x): Here the np.char.split() is called with x as an argument to split the string element of x into a list of substrings based on the default delimiter (space) and returns a 1-dimensional numpy array r containing a single element which is a list of the substrings.

Pictorial Presentation:

NumPy String: Split the element of a given array with spaces

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to remove the trailing whitespaces of all the elements of a given array.
Next: Write a NumPy program to split the element of a given array to multiple lines.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/numpy/python-numpy-string-exercise-10.php