translate(): Mapping and Removing Characters

translate() , maketrans() : Search replace and delete of set of chars.
str_update=str_input.maketrans(str_search,str_replace,str_delete)
str_search : Required, Chars to be searched
str_replace: Required, Chars to be replaced ( mapped to searched chars )
str_delete : Optional, Chars to be replaced with None ( deleted in final string )

Length of str_search should be equal to length of str_replace
the method maketrans() returns a dictionary ( str_update ) with chars mapped for search and replace and this can be used for translate().
str_search='abc'  # search chars str_replace='xyz' # replace chars str_delete='pqr'  # delete chars 
str_input='abcdefghpqr' #input string 
str_update=str_input.maketrans(str_search,str_replace,str_delete)
print(str_update) # dictionary output with chars mapped. print("input string : ",str_input)print("Output string: ",str_input.translate(str_update))
Output
{97: 120, 98: 121, 99: 122, 112: None, 113: None, 114: None}input string :  abcdefghpqrOutput string:  xyzdefgh

The `translate()` function works with `maketrans()` to replace or remove characters in a string based on a translation table. `maketrans()` helps define a mapping for character replacements or deletions, which `translate()` applies.

Syntax

str.translate(translation_table)

Example 1: Basic Mapping with translate()

Mapping characters with `maketrans()` and applying with `translate()`.
str_input = "abcdef"table = str.maketrans("abc", "xyz")print(str_input.translate(table))
Output:
xyzdef

Example 2: Mapping and Removing Specific Characters

Removing specific characters from a string by passing `None` in `maketrans()`.
str_input = "hello world!"table = str.maketrans("", "", "aeiou")print(str_input.translate(table))
Output:
hll wrld!

Example 3: Multiple Character Mappings with translate()

Using `translate()` to swap multiple characters in a string.
str_input = "apple pie"table = str.maketrans("ap", "xy", "e")print(str_input.translate(table))
Output:
xyyl yi

Applications of translate()

  • Data Cleaning: Useful for removing unwanted characters in text processing.
  • Encryption and Encoding: Basic character substitution in simple ciphers.
  • Text Normalization: Helpful for replacing unwanted characters in structured data.
All String methods