Python String Translate Exercise
Write a program in Python to replace a, b with 1, 3 respectively in a string.
Solution
The translate method enables us to map the characters in a string, replacing those in one table by those in another. And, the 'maketrans' function in the string module, makes it easy to create the mapping table.
Syntax of Python translate()
str. translate(table[, deletechars])
Here, table is the required parameter, it is translation table, created by using maketrans() function and deletechars is the list of characters removed from the string.
This is the following code to replace a, b with 1, 3 respectively in a string.
import string
def test():
a = 'axsxxbdreafeyb'
t = string.maketrans('ab', '12')
print a
print a.translate(t)
test()
Output of the above code
Related Articles
Python program for Prime NumberOdd Even Program in Python
Python program to convert Celsius to Fahrenheit
Python Convert XML to CSV
Python Text to Speech
Python send mail to multiple recipients using SMTP server
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml