[Tutor] Replacing comma with dot and dot with comma in a string

Manprit Singh manpritsinghece at gmail.com
Sat May 1 03:23:54 EDT 2021


Dear sir ,

consider a string
st = "as.hjtk,rah,lop."

Now I have to  replace all commas with dots and all dots with commas. The
answer should be 'as,hjtk.rah.lop,'
Now for doing this i have used translate and maketrans as below:
st = "as.hjtk,rah,lop."
trans = str.maketrans({",": ".", ".":","})
ans = st.translate(trans)
print(ans)
which gives the right answer.
Just need to know if my understanding iabout translate and maketrans is
correct or not ?
I have passed a dict inside maketrans, for making a  translation table for
to be passed to translate . the dict contains the first key value pair as
"," : "." because the comma needed to be replaced with a dot similarly
second key value pair is "." : "," because a dot is needed to be replaced
with a comma in the string .

Regards
Manprit Singh


More information about the Tutor mailing list