w3resource

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

NumPy String: Exercise-19 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-19.php