Python 3 String translate() Method
Python 3’s string library provides a method called translate()
that allows you to map each character in a string to a different character or to remove characters altogether. In this article, we will discuss the translate()
method, its syntax, parameters, and examples of how to use it.
Syntax
The translate()
method in Python 3 has the following syntax:
string.translate(table)
Parameters
The translate()
method requires one parameter:
table
– A translation table containing the mapping between the original characters and the new characters.
Table
The table
parameter is a dictionary-like object that maps characters in the input string to their translations. It can be created using the str.maketrans()
method.
Here is an example of how to create a translation table:
table = str.maketrans('abc', '123')
This creates a table that maps a
to 1
, b
to 2
, and c
to 3
.
Example
Here is a simple example of how to use the translate()
method:
string = "hello world"
table = str.maketrans('abc', '123')
new_string = string.translate(table)
print(new_string)
Output:
hello world
Since the input string does not contain any of the characters in the translation table, the output string is the same as the input.
Use Case: Removing Non-Alphanumeric Characters
One common use case for the translate()
method is to remove non-alphanumeric characters from a string. Here’s how to do it:
string = "This is a test! #$%&^*!"
table = str.maketrans('', '', string.punctuation)
new_string = string.translate(table)
print(new_string)
Output:
This is a test
In this example, we use the string.punctuation
attribute to get a string containing all the punctuation characters. We then create a translation table that maps each punctuation character to None
, effectively removing them from the string.
Conclusion
The translate()
method is a powerful tool for mapping or removing characters in a string. By using the str.maketrans()
method, you can easily create a translation table that allows you to change any characters you want. Be sure to experiment with the translate()
method and see what other use cases you can come up with.