Q:

Write a program in Python to replace a, b with 1, 3 respectively in a string

0

Write a program in Python to replace a, b with 1, 3 respectively in a string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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', '13')
    print a
    print a.translate(t)
test()
Output of the above code

axsxxbdreafeyb

1xsxxbdreafey3

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now