NumPy strings.mod()

The numpy.strings.mod() function performs element-wise string formatting (interpolation) using the old-style % formatting in Python. It allows inserting values into string templates stored in NumPy arrays.

Syntax

</>
Copy
numpy.strings.mod(a, values)

Parameters

ParameterTypeDescription
aarray_like, with np.bytes_ or np.str_ dtypeArray of string templates where placeholders (%) are used for formatting.
valuesarray_likeArray of values that will be interpolated into the corresponding string templates.

Return Value

Returns an output array containing formatted strings, with data type depending on the input (np.str_ or np.bytes_).


Examples

1. Basic String Formatting Using NumPy strings.mod()

In this example, we use numpy.strings.mod() to insert values into string templates.

</>
Copy
import numpy as np

# Define an array of string templates
templates = np.array(["I like %s", "My favorite fruit is %s", "%s is delicious"], dtype=np.str_)

# Define an array of values to insert
values = np.array(["apple", "banana", "cherry"], dtype=np.str_)

# Apply string interpolation
result = np.strings.mod(templates, values)

# Print the formatted strings
print(result)

Output:

['I like apple' 'My favorite fruit is banana' 'cherry is delicious']

2. Formatting with Integers

We can also use integer values in the placeholders.

</>
Copy
import numpy as np

# Define an array of string templates
templates = np.array(["I bought %d apples", "You have %d bananas"], dtype=np.str_)

# Define integer values to insert
values = np.array([5, 3], dtype=np.int_)

# Apply string interpolation
result = np.strings.mod(templates, values)

# Print the formatted strings
print(result)

Output:

['I bought 5 apples' 'You have 3 bananas']