Python string translate() function is used to replace specific characters in a string based on a translation table, which is created using the maketrans() method.
Syntax
string.translate(table)
Parameters
table(required): A dictionary or a mapping table that describes how to perform the replacement.
Return value
Returns a string where specified characters are replaced according to the provided translation table.
Visual Representation
Example 1: How to Use translate() Method
dt = "Bilbo Baggins"
transTable = dt.maketrans("B", "K")
print(dt.translate(transTable))
Output
Kilbo Kaggins
Example 2: Translation/Mapping using a translation table
s1 = "Modric"
s2 = "Neymar"
s3 = "Mbappe"
string = "footballer"
print("Original string:", string)
translation = string.maketrans(s1, s2, s3)
# translate string
print("Translated string:", string.translate(translation))
Output
Original string: footballer
Translated string: feetllm
Example 3: Translation with a manual translation table
Here We manually create a translation table (in the form of a dictionary).
When using a dictionary, ASCII codes must be used instead of characters.
trans_table = {82: None, 111: None, 104: 111}
str = "Rohit"
print("Original string:", str)
# translate string
print("Translated string:", str.translate(trans_table))
Output
Original string: Rohit
Translated string: oit
The R is removed, the o is removed, and the h is replaced by o. Thus, “Rohit” becomes “oit”.
Example 4: Remove Punctuation from a String in Python
import string
s1 = "Cristiano Ronaldo is a Portuguese professional footballer."
trans_table = str.maketrans("", "", string.punctuation)
translated_string = s1.translate(trans_table)
print(translated_string)
Output
Cristiano Ronaldo is a Portuguese professional footballer
You can see that the punctuation at the end of the original string (the period) is removed.
Example 5: Remove Vowels from a String
s1 = "Cristiano Ronaldo"
vowels = "aeiouAEIOU"
trans_table = str.maketrans('', '', vowels)
text_without_vowels = s1.translate(trans_table)
print(text_without_vowels)
Output
Crstn Rnld
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.