Python String translate()

Python’s in-built method for the String class, str.translate(), is used to map a string with a translation table. The translate() method simply converts it using the translation table rules.

Let’s understand more about the method in this article.


Syntax of Python String translate()

Since the translate() function returns a new string with each character in the string replaced using the given translation table, it’s inputs are a string and a table, returning a string.

But, since this is a method belonging to the str class, we only call them using the input string object.

out_str = in_str.translate(translation_table)

Here, translation_table is a translation table containing relevant mappings.

Although we know what a translation table is, we don’t know how it is constructed yet. Let us understand that as well.


Construct the translation table using maketrans()

We can make the translation table using the maketrans() method.

Since any mapping can work as a translation table, an existing Python Dictionary can also be made into a translation table.

Syntax of maketrans():

We always call maketrans() using str.maketrans(), where str is the built-in keyword representing Python’s string class.

If there is only one argument, it must be a dictionary mapping (dict_map) Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals.

translation = str.maketrans(dict_map)

If there are two arguments, they must be strings of equal length (str_x and str_y), and in the resulting dictionary, each character in x will be mapped to the character at the same position in y.

translation = str.maketrans(str_x, str_y)

If there is a third argument, it must be a string (str_z), whose characters will be mapped to None in the result.

translation = str.maketrans(str_x, str_y, str_z)

Perform the translation

We can now perform the translation of the output string from the input string using python string translate(), after constructing the translation table using maketrans().

Let’s take examples showing all three ways of using maketrans(), to make your understanding complete.

Using a Dictionary mapping

# Input string
inp_str = 'Hello from AskPython'

# Create a Dictionary for the mapping
dict_map = dict()

# We shift every letter from A-z by 9 units
# using ord() to get their ASCII values
for i in range(ord('A'), ord('z')):
    dict_map[chr(i)] = chr(i + 9)

# Convert the dictionary mapping to a translation table
translation = str.maketrans(dict_map)

# Perform the translation
out_str = inp_str.translate(translation)

print(out_str)

The output will be the string containing every character shifted right by 9 places.

Output:

Qnuux o{xv J|tYA}qxw

Using Direct Mapping

Here is a simpler example that utilizes direct mapping and constructs a translation table using 2 arguments, which are then passed to the input string translate() function.

s = 'ABCDBCA'

translation = s.maketrans('A', 'a')
print(s.translate(translation))

translation = s.maketrans('ABCD', 'abcd')
print(s.translate(translation))

This translates the first ‘A‘ character to ‘a‘, and then converts ‘ABCD‘ to ‘abcd‘, as shown below.

Output:

aBCDBCa
abcdbca

Again, since this option specifies that the length of the two strings be the same, anything else will raise a ValueError Exception.

s = 'ABCDBCA'

translation = s.maketrans('Ab', 'a')
print(s.translate(translation))

Output:

ValueError: the first two maketrans arguments must have equal length

Using a None mapping

Here is a simpler example which utilizes None mapping by invoking maketrans() using 3 arguments.

# Input string
inp_str = 'Hello from AskPython'

translation = str.maketrans('As', 'ab', 'e')

# Perform the translation
out_str = inp_str.translate(translation)

print(out_str)

This will replace ‘As’ with ‘ab’, while replacing ‘e’ with None, effectively removing the character from the string.

Output:

Hllo from abkPython

Construct a Dictionary mapping Directly

We can construct a Dictionary mapping directly into maketrans() when we call the function.

# Input string
inp_str = 'Hello from AskPython'

translation = str.maketrans({ord('A'): 'a', ord('s'): 'b', ord('e'): None})

# Perform the translation
out_str = inp_str.translate(translation)

print(out_str)

This will give the same output as the previous snippet since they have the same translation tables.

Output:

Hllo from abkPython

NOTE: We can map a Unicode value (ord() keys in the mapping Dictionary) to any string, unlike that of passing strings as arguments into maketrans(). So, a mapping like {ord('A'): 'hello'} is valid, and replaces ‘A‘ with ‘hello‘.


Conclusion

In this article, we learned how we can use the python string translate() method to perform string translation based on a translation table in Python. We also looked at how we could construct such a table using various ways.

References