Changing numbers into characters using dictionaries

snoe case.nelson at gmail.com
Thu Jan 26 22:15:51 CET 2006


Ok there's a couple things going on here.

> t = text.split('@') // splits the digits/blocks apart from each other
this will give you a list:
['', '7706', '7002', '7075', '7704']

You may want to change the line to skip the first empty value:
t = text.split('@')[1:]

Next your loop.
> something = 1
> while True:
>      var = str(a[t[something]])
>      print var,
> // I want it to change "@7704 at 7002@7075 at 7704" into "lawl"

I think what you want to do here is loop through your list t, take the
values out of the encrypted text and lookup that value in a.

In python, you can loop through a list like this:

for encrypted_char in t:
    var = a[encrypted_char]
    print var,

now instead of printing each char as you decrypt it you should collect
them first and do the print at the end. So you get:

temp_list = []
for encrypted_char in t:
    var = a[encrypted_char]
    temp_list.append(var)
print ''.join(temp_list)

This still won't help with the key error you're getting though, but you
can catch that error by surrounding your offending line with a
try/except block:

temp_list = []
for encrypted_char in t:
    try:
        var = a[encrypted_char]
        temp_list.append(var)
    except KeyError:
        print encrypted_char, "not in", a
        temp_list.append('?')
print ''.join(temp_list)

So your final script looks like this:
text = '@7704 at 7002@7075 at 7704' # some text
num = '213654' # Number
s1 = '700'
s2 = '770'
s4 = '707' # it adds these later on.
# splits the digits/blocks apart from each other
t = text.split('@')[1:]
a = {s2+num[3]:"l", s1+num[0]:"a", s4+num[5]:"w"}

temp_list = []
for encrypted_char in t:
    try:
        var = a[encrypted_char]
        temp_list.append(var)
    except KeyError:
        print encrypted_char, "not in", a
        temp_list.append('?')
print ''.join(temp_list)

Fixing either your initial text or your a dict depends on your
requirements.




More information about the Python-list mailing list