Menu Close

Python String translate() Method

python string translate

In this tutorial, you will learn all about the Python string translate function along with some examples.
Python string translate() method is used to replace some specified characters with another specified character. translate function in Python returns a new list.

In the previous tutorial, we have seen the Python string splitlines method to split the string on line breaks.

Python String translate() Method

Python string translate() method is used to replace some specified characters with another character described in a dictionary or in the mapping table.
If any character not specified in the dictionary or table. It will not replace any character.


translate function accepts a parameter as a dictionary. If you use a dictionary, you must be used the ASCII value instead of characters.

Syntax

The syntax of translate function in python is:-

string.translate(table)

Parameter

The translate function in Python is accept one parameter that is table.

  • table:- Required. either a dictionary or mapping table.

Return Value

The return value of string translate function in Python is new string where some specified characters replaced with another character.

Python string translate example

Here will use the Python string translate method with some examples so that you can understand easily.

Example 1:

In this example we will replace ‘H‘ and ‘V‘ with ‘T‘ AND ‘B‘ using translate method.

str = 'Hello Vishvajit'
mytable = {72: 84, 86: 66}
result = str.translate(mytable)
print(result)

Output

Tello Bishvajit

You can use the string maketrans method to create a mapping table.maketrans returns a dictionary like above mytable.

Example 2:

You can replace many characters using translate function in Python.

str = 'Hello Vishvajit'
x ='HV'
y = 'TB'
mytable = str.maketrans(x,y)
print(mytable)
result = str.translate(mytable)
print(result)

Output

Tello Bishvajit

Conclusion

In this article, you have learned the Python string translate method to replace specified characters with another character described in the dictionary or mapping table.
You must always remember that translate function in Python accept the only dictionary contain ASCII value, not characters.

I hope this article will help. If you like this article, please share it with your friends who want to learn Python programming.

Other string methods:


For More Information:- Click Here

Python String splitlines() Method
Python String maketrans() Method

Related Posts