Replacing Characters In A String Using Dictionary In Python
I have researched about character replacement using dictionaries but I still cannot get my code to work properly. My code goes like this: def encode(code,msg): for k in code:
Solution 1:
You can look at str.translate
or do:
''.join(code.get(ch, ch) for ch in msg)
Solution 2:
Use maketrans
and translate
:
fromstring import maketrans
msg.translate(maketrans(''.join(code.keys()), ''.join(code.values())))
Solution 3:
The problem is that you iterate on code instead on msg
Iterating on msg is what is done in Jon Clements' program, which can be written more explicitly as
print''.join(code[ch] if ch in code else ch for ch in msg)
Solution 4:
you're swapping x and e; it is overwriting your previous edits.
You should copy from an old string to a new one (or rather, an array of chars, since as Kalle pointed out strings are "immutable"/not editable), so that you don't overwrite characters you've already replaced:
defencode(code, message):
encoded = [c for c in message]
for i, c inenumerate(message):
try:
encoded[i] = code[c]
except KeyError:
passreturn''.join(encoded)
the other answers are library functions which do something like this, but they don't explain where you went wrong.
Solution 5:
python 3.2
use your own code it is ok.
def encode(code,msg):
for k in code:
msg = msg.replace(k,code[k],1)
return msg
## str.replace(old,new,[,count])
so when you loop in your code = {'e':'x','x':'e'}
first it gets the key "x" then the key "e" because dict isnot ordered
so, "Hendrix" turns into"Hendrie" then "Hendrie" turns into Hxndrix and
you are not having your result. but if you add1in your code
msg.replace(k,code[k],1) then it only will replace one letter per loop and you
have your result Try.
Post a Comment for "Replacing Characters In A String Using Dictionary In Python"