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.

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])
Sign up to request clarification or add additional context in comments.

Comments

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'

Comments

Your Answer

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.