The translate() method in Python String of Python programming returns a copy of the string where all the characters have been translated making use of a table which is constructed with the maketrans() function of the Python string module, optionally deleting every character found into the string deletechars.
Here is the syntax for translate() method:
str.translate(table[, deletechars]);
This method in Python string returns a translated copy of the string.
The following example shows the usage of translate() method. Under this, every vowel in a string is replaced by its vowel position -
#!/usr/bin/python from string import maketrans # Required to call maketrans function. intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"; print str.translate(trantab)
Below is the example to delete 'x' and 'm' characters from the string:
th3s 3s str3ng 2x1mpl2....w4w!!!
When the above program is run, it produces the following result:
#!/usr/bin/python from string import maketrans # Required to call maketrans function. intab = "aeiou" outtab = "12345" trantab = maketrans(intab, outtab) str = "this is string example....wow!!!"; print str.translate(trantab, 'xm')
This will produce the following results:
th3s 3s str3ng 21pl2....w4w!!!
Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.