Write a python program to get a string from a given string where all occurrences of its first character have been changed to ‘$’


# Find the first character of the string

char_1st = a[0]

#Replace  the first character

b = a.replace(char_1st, ‘$’)

#Print the changed  string

c = char_1st + b[1:]


Here is not a recommended way to do it, unless you are iteratively doing this (for each letter, many times), but another way to do it:

And I was wrong on the speed. Plus different in Python3.

import string
a = 'ababc'
firstchar = a[0]
trantab = string.maketrans(firstchar, '*')def translate(mystr, firschar):
trantab = string.maketrans(firstchar, '*')
return firstchar + string.translate(mystr[1:], trantab)def translate_iter(mystr, firschar, trantab):
return firstchar + string.translate(mystr[1:], trantab)def replace(mystr, firstchar):
return firstchar + mystr[1:].replace(firstchar, '*')In [29]: %timeit translate(a, firstchar)
1000000 loops, best of 3: 582 ns per loopIn [30]: %timeit replace(a, firstchar)
1000000 loops, best of 3: 240 ns per loopIn [32]: %timeit translate_iter(a, firstchar, trantab)
1000000 loops, best of 3: 376 ns per loop

Leave a Reply

Your email address will not be published. Required fields are marked *