0
Can someone help me with this code [(fixed)]
The code is too long for description so i will post it in the comments
5 Answers
+ 2
Since strings are immutable, they update their original value using the last value assigned.
I mean your code is same as
change = original.replace("Z","26")
It needs to be done like this
change = original.replace("a","1").replace("b",'2')...
you can use key-value pairs with a loop to avoid repeating.
+ 3
i recommend use dictionary of characters and numbers
alpha = {"a": 1, "b": 2, ...}
def text_to_number(s):
âres = []
âfor char in s:
ââif char in alpha:
âââres.append(alpha[char])
ââelse:
âââres.append(char)
âreturn "".join(res)
+ 2
b-l-a-n-k ,
first of all i wanted to mention, that way the encoding is done from character to number does not give unique numbers that can be decoded back.
"p" # and ""af" is giving the same result 16, same can happen to other combinations...
independent from this issue, the solution mentioned by *operand* to use a dict with the characters and the replscements should be the preferred way.
from string import ascii_lowercase as asc_lwr
asc_dic = {v: k for k, v in enumerate(asc_lwr, 1)} # fill dict with k, v (character, number) pairs
txt = "a quick brown fox jumps over the lazy dog"
new_txt = ""
for char in txt:
new_txt += str(asc_dic.get(char, char))
print(new_txt)
+ 1
I dunno what .join() is