w3resource

NumPy: Split the element of a given array to multiple lines

NumPy String: Exercise-11 with Solution

Write a NumPy program to split the element of a given array to multiple lines.

Sample Solution:-

Python Code:

# Importing necessary library
import numpy as np

# Creating a NumPy array containing a single string with newline characters
x = np.array(['Python\nExercises, Practice, Solution'], dtype=np.str)

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

# Splitting the single string in the array by line breaks
r = np.char.splitlines(x)

# Displaying the result after splitting the string by line breaks
print(r)

Sample Input:

['Python\\Exercises, Practice, Solution']

Sample Input:

(['Python\Exercises, Practice, Solution'], dtype=np.str)

Sample Output:

[list(['Python\\Exercises, Practice, Solution'])]

Explanation:

In the above exercise –

x = np.array(['Python\Exercises, Practice, Solution'], dtype=np.str): This line creates a numpy array x containing a single string. The string includes backslashes and commas.

r = np.char.splitlines(x): This code uses the numpy function np.char.splitlines() to split the string in x into substrings based on newline characters, and stores the result in the variable r.

Python-Numpy Code Editor:

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

Previous: Write a NumPy program to split the element of a given array with spaces.
Next: Write a NumPy program to make all the elements of a given string a numeric string of 5 digits with zeros on its left.

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.