String translate() Method in Python

Python String translate() Method

In Python, the translate() method is a built-in string method used for replacing characters in a string based on a translation table. It is a powerful tool for performing character-level substitutions or deletions.

The translate() method is often used to efficiently process large strings where multiple characters need to be replaced. It is faster than manually looping through the characters and applying replacements.

Here's the syntax of the translate() method:

str.translate(table)

Parameters:

  • table: A translation table created using the str.maketrans() method or a dictionary that maps the ordinal integers of characters to their replacement counterparts.

The str.maketrans() method is used to create the translation table. It has the following syntax:

str.maketrans(x, y, z)

Parameters:

  • x: If only one argument is provided, it must be a dictionary where each character in the key is mapped to its corresponding replacement.
  • y: If two arguments are passed, it should be strings of equal length, where each character in the first string is mapped to the character at the same position in the second string.
  • z: If three arguments are provided, it should be a string containing characters that will be deleted from the input string.

Let's see some examples to understand how the translate() method works:

Using str.maketrans() with two strings x and y.

original_string = "Hello, world!"
translation_table = str.maketrans("el", "xy")
translated_string = original_string.translate(translation_table)

print(translated_string)  # Output: "Hxxyo, worxd!"

Using str.maketrans() with three arguments to delete certain characters.

original_string = "Hello, world!"
translation_table = str.maketrans("", "", "o")
translated_string = original_string.translate(translation_table)

print(translated_string)  # Output: "Hell, wrld!"

Using a custom dictionary for translation.

original_string = "Python is awesome!"
translation_dict = {ord('a'): 'A', ord('e'): 'E', ord('o'): 'O'}
translation_table = str.maketrans(translation_dict)
translated_string = original_string.translate(translation_table)

print(translated_string)  # Output: "PythOn is AwEsOmE!"

In these examples, the translate() method replaces or removes characters according to the specified translation table. Note that the translate() method returns a new string with the replacements, leaving the original string unchanged.