Open In App

Python String translate() Method

Last Updated : 16 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python String translate() returns a string that is a modified string of givens string according to given translation mappings. 

What is translate() in Python?

translate() is a built-in method in Python that is used to replace specific characters in a string with other characters or remove them altogether. The translate() method requires a translation table that maps the characters to be replaced to their replacements. This table can be generated using the maketrans() method, which takes two arguments: the characters to be replaced and their replacements.

Python String translate() Syntax

str.translate(translation_table)

Example:

In the given example, we are using str.translate() method is used to translate a string by specifying a mapping using ASCII values.

Python3




# specifying the mapping using ASCII 
translation = {103: None, 101: None, 101: None}
 
string = "geeks"
 
# translate string
print("Translated string:",
       string.translate(translation))


Output: 

Translated string: ks

Python String translate() Examples 

There are two ways to translate are:

  • Python String translate() with mapping as a dictionary.
  • Mapping using maketrans().

Translation/Mapping with translate() with manual translation table

In this example, we are going to see how to use Python string translate() methods with a dictionary.

Python3




# Python3 code to demonstrate
# translations without
# maketrans()
 
# specifying the mapping
# using ASCII
table = { 119 : 103, 121 : 102, 117 : None }
 
# target string
trg = "weeksyourweeks"
 
# Printing original string
print ("The string before translating is : ", end ="")
print (trg)
 
# using translate() to make translations.
print ("The string after translating is : ", end ="")
print (trg.translate(table))


Output :

The string before translating is : weeksyourweeks
The string after translating is : geeksforgeeks

Translation/Mapping using a translation table with translate()

In the given example, the vowels are replaced with digits with the use of maketrans() and translate() in Python.

Python3




# Define the translation table
table = str.maketrans('aeiou', '12345')
 
# Apply the translation to a string
text = 'this is a test'
translated_text = text.translate(table)
 
print(translated_text)  # 'th3s 3s 1 t2st'


Output :

th3s 3s 1 t2st

Python maketrans()

The maketrans() method is a built-in string method in Python that generates a translation table. It is primarily used in conjunction with the translate() method to perform character-by-character translations or deletions.

Python maketrans() Syntax

Syntax: maketrans(str1, str2, str3) 

Parameters: 

  • str1: Specifies the list of characters that need to be replaced. 
  • str2: Specifies the list of characters with which the characters need to be replaced. 
  • str3: Specifies the list of characters that need to be deleted.

Returns: Returns the translation table which specifies the conversions that can be used by translate()

Example:

In this code, we are demonstrating how to use str.translate() with a translation table created using string.maketrans() to modify a string by replacing and deleting specific characters.

Python3




# Python 3 Program to show working
# of translate() method
 
# First String
firstString = "gef"
 
# Second String
secondString = "eks"
 
# Third String
thirdString = "ge"
 
# Original String
string = "geeks"
print("Original string:", string)
 
translation = string.maketrans(firstString,
                               secondString,
                               thirdString)
 
# Translated String
print("Translated string:",
       string.translate(translation))


Output : 

Original string: geeks
Translated string: ks

Use case of translate() and maketrans() Method

Remove Vowels from a String

In the given example, we are using the Maketrans() and translate()  to remove the vowels in the string in Python.

Python3




text = "Hello, world!"
vowels = "aeiouAEIOU"
table = str.maketrans("", "", vowels)
translated_text = text.translate(table)
 
print(translated_text) # Output: "Hll, wrld!"


Output:

Hll, wrld!

Remove Punctuation from a String

In the given example, we are using the Maketrans() and translate()  to remove the punctuation mark in the string in Python.

Python3




import string
 
text = "Hello, world! This is a test."
table = str.maketrans("", "", string.punctuation)
translated_text = text.translate(table)
 
print(translated_text) # Output: "Hello world This is a test"


Output:

Hello world This is a test


Previous Article
Next Article

Similar Reads

Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace & expandtabs())
Some of the string methods are covered in the below sets.String Methods Part- 1 String Methods Part- 2More methods are discussed in this article1. strip():- This method is used to delete all the leading and trailing characters mentioned in its argument.2. lstrip():- This method is used to delete all the leading characters mentioned in its argument.
4 min read
Python - Sympy Curve.translate() method
In Sympy, the function Curve.translate() is used translate the given curve by the given values of x, y. It translates the curve along with both the directions i.e. along x-axis and y-axis. Syntax: Curve.translate(x, y) Parameters: x: translation value along x-axis y: translation value along y-axis Returns: Translated Curve Example #1: # import Curv
1 min read
numpy string operations | translate() function
numpy.core.defchararray.translate(arr, table, deletechars=None) is another function for doing string operations in numpy. For each element in arr, it returns a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table. If ther
1 min read
maketrans() and translate() functions in Python
In the world of programming, seldom there is a need to replace all the words/characters at once in the whole file python offers this functionality using functions translate() and its helper functions maketrans(). Both functions are discussed in this article. maketrans() maketrans() function is used to construct the transition table i.e specify the
3 min read
Python | Pandas Series.str.translate()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.translate() is one of most important and complex string method. It uses a translate table to translate the caller series of s
2 min read
Build an Application to translate English to Hindi in Python
In these articles, We will write python scripts to translate English word to Hindi word and bind it with the GUI application. We are using the English-to-Hindi module to translate the English word into the Hindi word. Installation: Run this code into your terminal: pip install englisttohindi Approach: Import English to Hindi modules.Create an objec
2 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python | Check if given string can be formed by concatenating string elements of list
Given a string 'str' and a list of string elements, write a Python program to check whether given string can be formed by concatenating the string elements of list or not. Examples: Input : str = 'python' lst = ['co', 'de', 'py', 'ks', 'on'] Output : False Input : str = 'geeks' lst = ['for', 'ge', 'abc', 'ks', 'e', 'xyz'] Output : True Approach #1
5 min read