w3resource

NumPy: Make all the elements of a given string to a numeric string of 5 digits with zeros on its left


12. Zero-Pad Numeric Strings to 5 Digits

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:

NumPy String: Make all the elements of a given string to a numeric string of 5 digits with zeros on its left

For more Practice: Solve these Related Problems:

  • Create a function that pads each numeric string in an array with leading zeros to ensure a total length of 5.
  • Implement a solution using np.char.zfill and verify that strings shorter than 5 characters are correctly padded.
  • Test the padding function on an array containing numbers in different formats (integers, floats as strings).
  • Chain the zero-padding operation with a conversion back to integers to check consistency with original numeric values.

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.



Follow us on Facebook and Twitter for latest update.