NumPy: Make all the elements of a given string to a numeric string of 5 digits with zeros on its left
NumPy String: Exercise-12 with Solution
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:
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 to multiple lines.
Next: Write a NumPy program to replace "PHP" with "Python” in the element of a given array.
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://w3resource.com/python-exercises/numpy/python-numpy-string-exercise-12.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics