NumPy: Make all the elements of a given string to a numeric string of 5 digits with zeros on its left
Write a NumPy program to make all the elements of a given string to a numeric string of 5 digits with zeros on its left.
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:
(['2', '11', '234', '1234', '12345'], dtype=np.str)
Sample Output:
Original Array: ['2' '11' '234' '1234' '12345'] Numeric string of 5 digits with zeros: ['00002' '00011' '00234' '01234' '12345']
Explanation:
In the above code –
x = np.array(['2', '11', '234', '1234', '12345'], dtype=np.str): This line creates a one-dimensional numpy array x of strings.
r = np.char.zfill(x, 5): This line applies the np.char.zfill() function to each element of the array x. The function pads each string in the array with zeros to the left until the width of the string becomes 5, and returns a new array. The resulting array is assigned to the variable r.
Pictorial Presentation:
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