1

Please anybody clarify my doubt!!!! I have already seen the following posts of same question on stack overflow but still not getting the desired output.I'm not understanding why my code not giving the desired output using the same code as given on stack overflow.I want to ask what was i doing wrong in this code to replace one character in string occuring everywhere.I want to replace the key value occuring everywhere in the string into its mapped value of the dictionery.Please look at my code below:-

for _ in range(input()):
 n=input()
 c={}
 for i in range(n):
 a,b=raw_input().split()
 #print ord(a),ord(b)
 c[a]=b
 s=raw_input() 
 for i in c.keys():
 s.replace(i,c[i])
 print s 
input:- desired output:- Getting output:-
4 3 5
2 01800.00 01800.00
5 3 0.00100 0.00100
3 1 00321.330980 0xd21#dd098x 
5
0
01800.00
0
0.00100
3
x 0
d 3
# .
0xd21#dd098x

But i am getting the same input string as output also,don't getting what is the problem in code.

Anybody please help me.

falsetru
371k68 gold badges768 silver badges659 bronze badges
asked Mar 12, 2017 at 7:50

2 Answers 2

2

str.replace does not change the string in-place, but returns a new replaced string.

>>> s = 'ax'
>>> s.replace('a', 'b') # returns a new string
'bx'
>>> s # the string that `s` refers does not change
'ax'

You need to assign the returned string back to the variable:

s = s.replace(i, c[i])
answered Mar 12, 2017 at 8:39
0

If you want to replace multiple character, you might want to consider using str.translate():

>>> string = "abcdef"
>>> trans_table = str.maketrans({'a': 'x', 'c': 'y'})
>>> string.translate(trans_table)
'xbydef'
answered Mar 12, 2017 at 17:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.