w3resource

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


11. Split String Elements 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.

For more Practice: Solve these Related Problems:

  • Create a function that splits a long string into multiple lines at each comma or semicolon using np.char.splitlines.
  • Implement a solution that replaces a specific delimiter with a newline character and then splits the string accordingly.
  • Test the function on an array of strings containing various delimiters to ensure all line breaks are captured.
  • Combine the multiple-line split with a stripping operation to remove extraneous whitespace from each line.

Go to:


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.

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.