What is the numpy.char.translate() function in Python?

Overview

The char.translate() function in Python is used to return a copy of the string from a given input array whereby all the characters occurring in the optional argument deletechars are removed, and the remaining characters are mapped through the given table translation.

Syntax

char.translate(a, table, deletechars=None)

Parameter value

The char.translate() function takes the following parameter values:

  • a: This is the input array of strings or Unicode.
  • table: This is the translate mapping that is specified to perform the translations.
  • deletechars: This is the string character that needs to be removed.

Return value

The char.translate() function returns an array of strings or Unicode, depending on the input type that is passed to the function.

Code example

import numpy as np
# creating an array
myarray = np.array(["That", "There", "The"])
# creating a dictionary for the translation table
mydictionary = {"T": "B", "h": "l", "e": "a", "a": "o"}
# creating the translation table
mytable = "Thea".maketrans(mydictionary)
#printing the original array
print(myarray)
# implementing the char.translate() function
print(np.char.translate(myarray, mytable, deletechars=None))

Code explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an array of strings called myarray, using the array() function.
  • Line 7: We create a dictionary called mydictionary for the table parameter for translations.
  • Line 10: We create a table for translation by implementing the maketrans() method on the dictionary mydictionary.
  • Line 13: We print the original array of strings myarray.
  • Line 16: We implement the char.translate() function on the array myarray by passing mytable as the table parameter value. Then, we print the result to the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources