In the domain of programming, it is rare to need to replace all of the words/characters in a string at once. This article explains how to replace several characters in a string with a different set of characters. This is also known as string translation. Python has one built-in function for performing translations. It is called as Python translate() and along with its helper function maketrans() helps to translate a string.
Definition
- Python translate() is an in-built string method that returns a string where all the characters have been replaced/translated using the mapping table.
- The Python translate() function accepts a translation table created using the maketrans() function that replaces characters in the input string according to the mapping table.
What is a Mapping table?
To put it simply, the maketrans() method is a static method that generates a one-to-one mapping of a character to its translation/replacement.
Each character is given a Unicode representation for translation.
When the Python translate() method is called, this translation mapping is utilized to replace a character with its mapped character. The syntax for using this function is as below:
maketrans(string1, string2)
It will map the first character of string1 to the first character of string2 and so on. For example str1 = abcd and str2 = 1234. So, a will be mapped to 1, b to 2, c to 3, and so on. The maketrans() method returns a single string containing the mapping information.
Note – The length of the string arguments must be equal. Else the Python interpreter will throw a ValueError exception.
Python translate() Syntax
The syntax followed by Python translate() is as follows:
string.translate(table)
String translate() Parameters
Python translate() method accepts a single parameter:
- table – created using the maketrans() function, it contains a translation table having mappings between 2 characters
Return value from translate()
The translate() method returns a string with each character mapped to its matching character according to the translation table.
Example 1: Translation/Mapping using a translation table with translate()
In the program below, we will use the Python translate() method with the help of maketrans() function.
Example
# Python program to illustrate translate() using maketrans()
main_str = 'Will you have lunch with me?'
print('Original string:', main_str)
# declaring arguments for mapping using maketrans()
str1 = 'aeiou'
str2 = '12345'
# creating translation table
tran_table = main_str.maketrans(str1, str2)
# translating string
print('Translated string:', main_str.translate(tran_table))
Output
Original string: Will you have lunch with me?
Translated string: W3ll y45 h1v2 l5nch w3th m2?
Example 2: Translation/Mapping with translate() with manual translation table
We don’t use maketrans() to generate a translation table here; instead, we manually generate the mapping dictionary translation.
This translation is then applied to a string to provide the same result as the previous example.
Example
# Python program to illustrate translate() without using maketrans()
main_str = 'Will you have lunch with me?'
print('Original string:', main_str)
# translation table
# Keys written in Decimal (ASCII to Decimal)
tran_table = {97:'1', 101:'2', 105:'3', 111:'4', 117:'5'}
# translating string
print('Translated string:', main_str.translate(tran_table))
Output
Original string: Will you have lunch with me?
Translated string: W3ll y45 h1v2 l5nch w3th m2?
Example 3: maketrans() with Unequal Arguments
Example
main_str = 'Welcome Home'
# translation table
tran_table = main_str.maketrans('aei', '12345')
# translating string
print('Translated string:', main_str.translate(tran_table))
Output
Traceback (most recent call last):
File "", line 5, in
ValueError: the first two maketrans arguments must have equal length
Frequently Asked Questions
Q1. How do you translate text in Python?
Python has one built-in function for performing translations. It is called as Python translate() and along with its helper function maketrans() helps to translate a string.
Python translate() is an in-built string method that returns a string where all the characters have been replaced/translated using the mapping table.
First, we need to create a mapping table. To put it simply, the maketrans() method is a static method that generates a one-to-one mapping of a character to its translation/replacement. Each character is given a Unicode representation for translation.
And then when we call the Python translate() method, this translation mapping is utilized to replace a character with its mapped character
Q2. Which translator is used in Python?
As websites cater to an international audience, text translation from one language to another is becoming more popular. The python package that assists us with this is named translate. The following procedure can be used to install this package. It offers translation services for key languages.
pip install translate
And then we can use it in our program to translate simple sentences to different languages.
from translate import Translator
translator= Translator(to_lang="German")
translation = translator.translate("Good Morning!")
print(translation)
Output
Guten Morgen!
Q3. How do I use Google translate in Python?
Google Translate is a free service that converts words, phrases, and full web pages into over 100 different languages. We used Google API to create a Language Translator that can translate one language to another. Googletrans is a Python package that makes unauthorized Ajax calls to the Google Translate API to detect languages and translate text.
First, we will need to install the googletrans library/module by using pip.
pip install googletrans
Now we will import all the necessary libraries required for our translator:
from googletrans import Translator, constants
from pprint import pprint
Next, we will initialize the translator:
# init the Google API translator
translator = Translator()
Now, we will simply use the Python translate() function to get the desired translated text:
# Translate Spanish text to English text (by default)
translation = translator.translate("Hola Mundo")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")
Output
Hola Mundo (es) --> Hello World (en)
Leave a Reply