NumPy: Insert a space between characters of all the elements of a given array
NumPy String: Exercise-5 with Solution
Write a NumPy program to insert a space between characters of all the elements of a given array.
Sample Solution:-
Python Code:
# Importing necessary library
import numpy as np
# Creating a NumPy array containing strings
x = np.array(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str)
# Displaying the original array
print("Original Array:")
print(x)
# Using np.char.join to join elements of the array with a space character
r = np.char.join(" ", x)
# Displaying the result after joining elements with a space
print(r)
Sample Input:
(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str)
Sample Output:
Original Array: ['python exercises' 'PHP' 'java' 'C++'] ['p y t h o n e x e r c i s e s' 'P H P' 'j a v a' 'C + +']
Explanation:
In the above exercise –
x1 = np.array(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str): This line creates a 1-dimensional NumPy array x1 with 4 elements of string data type. The elements are ' python exercises ', 'PHP', 'Java', and 'C++'.
r = np.char.join(" ", x):
In the above code –
- The np.char.join() method takes two arguments:
- The first argument is the string to be used as a separator while joining the elements of the input array.
- The second argument is the array of strings to be joined.
- In this case, the separator used is a space character (" ") and the array of strings to be joined is 'x'.
- The resulting string after joining the elements of the input array is stored in the variable 'r'.
Pictorial Presentation:
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a NumPy program to make the length of each element 15 of a given array and the string centered / left-justified / right-justified with paddings of _.
Next: Write a NumPy program to encode all the elements of a given array in cp500 and decode it again.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://198.211.115.131/python-exercises/numpy/python-numpy-string-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics