NumPy: Split the element of a given array to multiple lines
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics