w3resource

NumPy: Add two zeros to the beginning of each element of a given array of string values


19. Prefix Elements with Zeros to Fixed Length

Write a NumPy program to add two zeros to the beginning of each element of a given array of string values.

Sample Solution:

Python Code:

# Importing necessary library
import numpy as np 

# Creating a NumPy array containing strings
nums = np.array(['1.12', '2.23', '3.71', '4.23', '5.11'], dtype=np.str)

# Displaying the content of the original array
print("Original array:")
print(nums)

# Adding two zeros to the beginning of each element of the array using np.char.add()
print("\nAdd two zeros to the beginning of each element of the said array:")
print(np.char.add('00', nums))

# Another method to add zeros to the beginning of each element using np.char.rjust()
print("\nAlternate method:")
print(np.char.rjust(nums, 6, fillchar='0')) 

Sample Output:

Original array:
['1.12' '2.23' '3.71' '4.23' '5.11']

Add two zeros to the beginning of each element of the said array:
['001.12' '002.23' '003.71' '004.23' '005.11']

Alternate method:
['001.12' '002.23' '003.71' '004.23' '005.11']

Explanation:

In the above code –

nums = np.array(['1.12', '2.23', '3.71', '4.23', '5.11'], dtype=np.str): This line creates a NumPy array of strings called nums with 5 elements.

np.char.add('00', nums): This line uses the add function from the np.char module to concatenate the string '00' to each element in the nums array.

np.char.rjust(nums, 6, fillchar='0'): This line uses the rjust() function from the np.char module to right justify each element in the nums array with a total width of 6 characters. The fillchar parameter is set to '0', which means that any empty space to the left of the string will be filled with zeroes.


For more Practice: Solve these Related Problems:

  • Create a function that adds two leading zeros to each element of an array of numeric strings using np.char.zfill.
  • Implement a solution that dynamically adjusts the number of zeros to ensure each string reaches a length of 15 characters.
  • Test the function on an array of mixed-length strings and verify that all elements are uniformly padded.
  • Chain the zero-prefixing with a conversion to a different numeric format (e.g., hexadecimal) for additional transformation.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to check whether each element of a given array starts with "P".
Next: Write a NumPy program to replace a specific character with another in a given array of string values.

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.