NumPy strings.multiply()

The numpy.strings.multiply() function performs element-wise string repetition. It multiplies each string element by an integer, effectively concatenating the string that many times.

Syntax

</>
Copy
numpy.strings.multiply(a, i)

Parameters

ParameterTypeDescription
aarray_like (StringDType, bytes_ or str_ dtype)Input array containing strings to be multiplied.
iarray_like (integer dtype)Array of integers specifying how many times each string should be repeated.

Return Value

Returns an array where each string element in a is repeated according to the corresponding integer in i. If i is less than 0, the result is an empty string.


Examples

1. Repeating a Single String

We repeat a single string multiple times.

</>
Copy
import numpy as np

# Define a string
fruit = np.array("apple", dtype="U")

# Repeat the string 3 times
result = np.strings.multiply(fruit, 3)

# Print the result
print("Repeated string:", result)

Output:

Repeated string: appleappleapple

2. Repeating Multiple Strings Element-Wise

We apply string repetition to an array of strings with corresponding repeat counts.

</>
Copy
import numpy as np

# Define an array of strings
fruits = np.array(["apple", "banana", "cherry"], dtype="U")

# Define an array of repetition counts
counts = np.array([2, 3, 1])

# Repeat each string accordingly
result = np.strings.multiply(fruits, counts)

# Print the result
print("Repeated strings:", result)

Output:

Repeated strings: ['appleapple' 'bananabananabanana' 'cherry']

3. Handling Zero and Negative Repetitions

Values of i less than or equal to zero result in an empty string.

</>
Copy
import numpy as np

# Define an array of strings
fruits = np.array(["apple", "banana", "cherry"], dtype="U")

# Define repetition counts, including zero and negative values
counts = np.array([2, 0, -1])

# Repeat each string
result = np.strings.multiply(fruits, counts)

# Print the result
print("Repeated strings:", result)

Output:

Repeated strings: ['appleapple' '' '']

Since banana was multiplied by 0 and cherry by a negative number, they resulted in empty strings.