Python 3 string translate() method
Python 3 String translate() Method
Description
translate() method returns a copy of the string with all characters translated using the table (constructed using the maketrans() function in the string module), optionally deleting any characters found in the string _deletechars.
Syntax
Following is the syntax of the translate() method:
str.translate(table[, deletechars]);
Parameters
- table − You can create a translation table using the maketrans() helper function in the string module.
Return Value
This method returns a translated copy of a string.
Example
The following example shows the use of the translate() method. In this example, each vowel in a string is replaced with its vowel position.
#!/usr/bin/python3
from string import maketrans # Required to call the maketrans function
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is the string example....wow!!!";
print (str.translate(trantab))
Result
When running the above program, the following result is produced –
th3s 3s str3ng 2x1mpl2....w4w!!!
Example
The following is an example of removing the “x” and “m” characters from a string:
#!/usr/bin/python3
from string import maketrans # Required to call the maketrans function.
intab = "aeiouxm"
outtab = "1234512"
trantab = maketrans(intab, outtab)
str = "this is the string example....wow!!!";
print (str.translate(trantab))
Result
This will produce the following output –
th3s 3s str3ng 21pl2....w4w!!!