Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a shorter way to replace all letters in an input? – Python 3

I am making a thing that needs to replace all letters in the alphabet taken from a user’s input but I think just doing it this way is way too long. Is there a better way to do this?

Im using python 3, b in the code is the input, and dot is the name of the list with stuff to replace

a1 = b.replace("a", dot[0])
  a2 = a1.replace("b", dot[1])
  a3 = a2.replace("c", dot[2])
  a4 = a3.replace("d", dot[3])
  a5 = a4.replace("e", dot[4])
  a6 = a5.replace("f", dot[5])
  a7 = a6.replace("g", dot[6])
  a8 = a7.replace("h", dot[7])
  a9 = a8.replace("i", dot[8])
#.... Continues

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

An idea is to convert the character into an integer, add 1 to it and then cast the resultant integer to char. You can achieve this using the builtin methods ord and chr.

prev=b

for i in range(26):
   cur=prev.replace(chr(ord('a')+i), dot[i])
   prev=cur
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading