Python str.translate() function


In Python, the str.translate() method is used to replace characters in a string based on a translation table. This method is particularly useful for performing character substitutions, deletions, or transformations in a string efficiently.

Syntax

str.translate(table)
  • table: A translation table that maps Unicode ordinals (integer representations of characters) to their corresponding replacement characters. This table can be created using the str.maketrans() method.

Creating a Translation Table

To use str.translate(), you typically create a translation table using str.maketrans(). This function allows you to define mappings from characters to their replacements in a straightforward manner.

Example Usage

  1. Basic character replacement:
# Create a translation table translation_table = str.maketrans("abc", "123") # Original string text = "abcde" # Translate the string using the table translated_text = text.translate(translation_table) print(translated_text) # Output: "123de"

In this example, the characters 'a', 'b', and 'c' are replaced with '1', '2', and '3', respectively.

  1. Multiple character replacements:

You can replace multiple characters at once:

translation_table = str.maketrans("abc", "xyz") text = "abcdef" translated_text = text.translate(translation_table) print(translated_text) # Output: "xyzdef"

Here, 'a' is replaced with 'x', 'b' with 'y', and 'c' with 'z'.

  1. Deleting characters:

If you want to delete certain characters from a string, you can create a translation table that maps those characters to None:

translation_table = str.maketrans("", "", "aeiou") # Delete vowels text = "Hello, World!" translated_text = text.translate(translation_table) print(translated_text) # Output: "Hll, Wrld!"

In this example, all vowels ('a', 'e', 'i', 'o', 'u') are removed from the string.

  1. Using Unicode characters:

You can also use Unicode characters in the translation table:

translation_table = str.maketrans("abc", "123") text = "abcñö" translated_text = text.translate(translation_table) print(translated_text) # Output: "123ñö"

The characters 'a', 'b', and 'c' are replaced, while 'ñ' and 'ö' remain unchanged.

Summary

  • Use str.translate() to replace characters in a string based on a translation table created with str.maketrans().
  • You can perform character substitutions, deletions, and transformations efficiently with this method.
  • This approach is particularly useful for manipulating strings where specific character patterns need to be modified or removed.
  • It's a powerful tool for text processing, especially when working with large strings or needing to perform multiple transformations at once.