Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Created June 29, 2020 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IndhumathyChelliah/5be6504615b8e4e091f08d2547f76250 to your computer and use it in GitHub Desktop.
Save IndhumathyChelliah/5be6504615b8e4e091f08d2547f76250 to your computer and use it in GitHub Desktop.
#two string of equal length are specified
s1="py"
s2="ji"
s3="python"
#maketrans returns the translation table to be used by translate() function.
table=s3.maketrans(s1,s2)
#ascii value of p=112,j=106,y=121,i=105
#p is translated to j, y is translated to i
print (table)#{112: 106, 121: 105}
#translation table is used by translate() function.
#In string "python", "p" is translated to "j" and "y" is translated to "i"
print (s3.translate(table))#Output:jithon
#two string of not same length given.It will raise ValueError.
st1="ab"
st2="cdcd"
st3="abcd"
#two strings should be of same length
#table1=st3.maketrans(st1,st2)
#print (table1)#Output:ValueError: the first two maketrans arguments must have equal length
# three strings are mentioned.
s4="abc"
s5="def"
s6="c" #characters to be deleted
s7="abcde"
table2=s7.maketrans(s4,s5,s6)
#ascii value of a=97,d=100,b=98,e=101,c=99
#since "c" character to be deleted, translated value is mentioned as "None"
print (table2)#Output:{97: 100, 98: 101, 99: None}
# In string "abcde" , "ab" is replaced by "de" and "c" is deleted.
print(s7.translate(table2))#Output:dede
#only one string is mentioned.If one string is mentioned ,it should be in dictionary format.
str1={'a':'c','b':'d'}
str2="abcd"
table3=str2.maketrans(str1)
print (table3)#Output:{97: 'c', 98: 'd'}
#in string "abcd", "a" is translated to "c" and "b" is translated to "d"
print (str2.translate(table3))#Output:cdcd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment