NumPy strings.translate()

The numpy.strings.translate() function modifies each string element in an array by mapping its characters through a translation table and optionally removing specified characters.

Syntax

</>
Copy
numpy.strings.translate(a, table, deletechars=None)

Parameters

ParameterTypeDescription
aarray-like (np.bytes_ or np.str_ dtype)Array of strings to be translated.
tablestr (length 256)A translation table that maps characters to their replacements.
deletecharsstr, optionalCharacters to be removed from the strings.

Return Value

Returns an array of translated strings with modifications as per the provided table and deleted characters.


Examples

1. Replacing Characters in Strings

We replace specific characters in a list of fruit names using a translation table.

</>
Copy
import numpy as np

# Define an array of fruit names
fruits = np.array(['apple', 'banana', 'cherry'], dtype=np.str_)

# Create a translation table: replacing 'a' with 'o' and 'e' with 'i'
translation_table = str.maketrans('ae', 'oi')

# Apply the translate function
translated_fruits = np.strings.translate(fruits, translation_table)

# Print the results
print("Original Strings:", fruits)
print("Translated Strings:", translated_fruits)

Output:

Original Strings: ['apple' 'banana' 'cherry']
Translated Strings: ['oppli' 'bonono' 'chirry']

2. Removing Specific Characters

We remove specific characters from strings using the deletechars parameter.

</>
Copy
import numpy as np

# Define an array of fruit names
fruits = np.array(['apple', 'banana', 'cherry'], dtype=np.str_)

# Specify characters to delete ('a' and 'e')
delete_chars = 'ae'

# Apply the translate function with deletechars
modified_fruits = np.strings.translate(fruits, {}, delete_chars)

# Print the results
print("Original Strings:", fruits)
print("Modified Strings:", modified_fruits)

Output:

Original Strings: ['apple' 'banana' 'cherry']
Modified Strings: ['ppl' 'bnn' 'chrry']

3. Combining Translation and Deletion

We replace some characters while removing others in a single operation.

</>
Copy
import numpy as np

# Define an array of fruit names
fruits = np.array(['apple', 'banana', 'cherry'], dtype=np.str_)

# Create a translation table: replacing 'e' with 'i'
translation_table = str.maketrans('e', 'i')

# Specify characters to delete ('a')
delete_chars = 'a'

# Apply the translate function
modified_fruits = np.strings.translate(fruits, translation_table, delete_chars)

# Print the results
print("Original Strings:", fruits)
print("Modified Strings:", modified_fruits)

Output:

Original Strings: ['apple' 'banana' 'cherry']
Modified Strings: ['ppli' 'bnn' 'chirry']

In this example, the character ‘a’ is removed while ‘e’ is replaced with ‘i’.