简体   繁体   中英

Multiple characters replace in a string python

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.

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])

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM