0
Better way?
Hello to everyone! What do you think about this code? Is there a better way to do this? dict = {"a":1, "b":2, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9, "j":10, "k":11, "l":12, "m":13, "n":14, "o":15, "p":16, "q":17, "r":18, "s":19, "t":20, "u":21, "v":22, "w":23, "x":24, "y":25, "z":26} palabra = input("Palabra: ").lower() palabraCifrada ="" for letra in palabra: if letra in dict: palabraCifrada += str(dict[letra]) else: palabraCifrada += letra print(palabraCifrada)
2 Respostas
+ 2
You can use comprehension to build the dictionary so you don't need to write it manually (helps reduce typo too). And use string::replace method to replace each character that exists in the dictionary by the dictionary item value, respectively.
And as much as possible, avoid using class name as variable (`d` rather than `dict` for example).
+ 1
# Lucio Fontana what about:
min = ord('a')-1
print(''.join(str(ord(chr)-min) if 'a' <= chr <= 'z' else chr for chr in palabra))
# avoid dict use/declaration
# use only palabra lowered user input
"""
however, this produce exactly same output as yours... but this is an one way encoding: you cannot decode output, unless you pass letters with 2 digits padded values and prefix original digits...
"""