w3resource

NumPy: Split the element of a given array with spaces


10. Split String Elements by Spaces

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

For more Practice: Solve these Related Problems:

  • Create a function that splits each element of a 1D string array by spaces and returns a list of lists.
  • Implement a solution that uses np.char.split to split the strings and then flattens the result into a 2D array.
  • Test the splitting function on strings with multiple consecutive spaces to verify proper tokenization.
  • Combine the split output with a join operation to reconstruct the original string and verify accuracy.

Go to:


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.

Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.