Home > Software design >  Is there a shorter way to replace all letters in an input? - Python 3
Is there a shorter way to replace all letters in an input? - Python 3

Time:04-29

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

CodePudding user response:

With the replacement in a dictionary we can use str.translate as long as you only need to replace single characters.

dotmap = {'e':'3', 'o':'0', ...}
txt = 'Hello world'

replacements = txt.maketrans(dotmap)
ntxt = txt.translate(replacements)

Which will return H3ll0 w0rld.

CodePudding user response:

I'm guessing dot contains the replacement characters for each alphabet. You could do something like

import string

s = 'example'
dot = '12345'

for c, cnew in zip(string.ascii_lowercase, dot):
    s = s.replace(c, cnew)

print(s)  # prints '5x1mpl5'

Explanation: zip pairs together the lowercase ASCII characters and the replacement characters. Then we get each pair in turn as c and cnew. s becomes the new string and the loop is repeated until either dot or the lowercase alphabet is exhausted.

CodePudding user response:

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
  • Related