Take the 2-minute tour ×

Alright, I did a bit of researching before I came here, and I didn't find anything that catered especially to what I wanted to find.

The problem is a little difficult, (at least, for me) so I'll do my best to explain it here.

Ok: So I've got a list of letters, that are taken from a string a user enters.

(They enter a string, then it's all broken down into individual letters and added to a list, where each letter is its own 'element')

Now I wanted to do this because I wanted to have all the letters inside this list to be translated into something else, depending on what I had 'set' each letter to be translated to.

I'm a bit confused as to how to do this, I could have a whole while loop that did the following:

Takes the first element, then runs the whole alphabet and numbers 1-9 by it. If it matched anything, it adds it to a new list.

The trouble is, it seems really inefficient to do this, and I am thinking their must surely be a better way to do this, I'll post what I am talking about below:

I can't get the code formatting to work correctly, and I'm just frustrated with it. Here's the code:

print("\t\t\tThe fun encryptor")
print("\n\n Please Enter the following string to be encrypted")
STRING = input("Entry: ")
#The string is to be encyrypted.
REPEAT = False

    OPPLIMIT += 1

# String Added to the Directory necessary
if "a" in DIRECTORY[0]:
    DIRECTORYT += [0.01]
elif "b" in DIRECTORY[0]:
    DIRECTORYT += [0.11]
elif "c" in DIRECTORY:
    DIRECTORYT += [1.11]

    #and so on and so forth


As you can see, it seems almost pointless to go through this all, is there an easier way to do it?

Perhaps using the for function thing?

share|improve this question
UGH, it doesn't show the screenshot: Here is the link: i1267.photobucket.com/albums/jj554/owatch/… –  Owatch Feb 15 '13 at 23:38
It's much more helpful to post code as text (e.g., a pastebin.com) than as a screenshot. We can't copy and paste a screenshot and try to run it ourselves. –  abarnert Feb 15 '13 at 23:44
@user1883304 You can convert the string to a list by doing DIRECTORY=list(STRING). –  Mike Feb 15 '13 at 23:47
Also, you really shouldn't give your variables all-caps names like this; it makes it very hard to read your code. See PEP 8 for more details. –  abarnert Feb 15 '13 at 23:48
@Mike: What part of his code makes you think he needs a list of the characters? –  abarnert Feb 15 '13 at 23:49
show 4 more comments

3 Answers

Not really sure what you are trying to do, but here are two approaches.

You could set up a dictionary with the letters and their translations, then do a lookup on this dictionary when your user enters a word.

codes = {}
codes['a'] = 9
codes['b'] = 133
# and so on
codes['z'] = 1

user_input = raw_input('Please enter a string: ')

translated_stuff = []

for letter in user_input:
   if letter in codes:

# a shorter way to do the above loop is
# translated_stuff = [codes[i] for i in user_input if i in codes]

print "Your translated stuff is : {}".format(''.join(translated_stuff))

Or, if you want that simply check if an input matches a set:

import string

match_list = string.letters + string.digits

user_input = raw_input('Please enter a string: ')
matched_stuff = [i for i in user_input if i in match_list]
share|improve this answer
Hey, I've tried using your way, but instead of using translated_stuff.append(codes[letter]) I am using COUNTLIMIT = len(User_input) while x != COUNTLIMIT: for letter in User_input[x]: if letter in TRvalues: Tdirectory += TRvalues[User_input[x]] x = x + 1 but I keep getting the error: 'float' object is not iterable –  Owatch Feb 16 '13 at 17:47
I'm sorry, there is no way that I can get this code to work properly. So annoying –  Owatch Feb 16 '13 at 17:49
why are you doing it that way? –  Burhan Khalid Feb 17 '13 at 4:35
@Owatch: If you tried completely different code and your completely different code didn't work, why not try Burhan Khalid's actual code? If you want to know why you're getting that TypeError, you'll have to show us the full traceback, and tell us where those other variables came from. (My guess is that User_input is a float or a list of floats, but I have no idea why, because you haven't shown the code that creates it. Maybe you're using Python 2.x and changed his raw_input to input anyway?) –  abarnert Feb 18 '13 at 19:02
add comment

First, instead of creating 26 separate variables named a, b, etc., just create a dict:

values = {'a': 0.01,
          'b': 0.11', 

Now, you can just do this:

for letter in DIRECTORY[0]:
    DIRECTORYT += [values[letter]]

Or, alternatively:

for letter in values:
    if letter in DIRECTORY[0]:
        DIRECTORYT += [values[letter]]

The difference between the two lies in how they handle duplicates. And I'm not sure which one you want (or, if you never have any dups, so it doesn't matter). Try executing both with different sample data until you get the idea.

As a side note, it's generally better to do:



DIRECTORYT += [values[letter]]

In other words, don't create a list if you don't need one.

But in this case, you may be able to replace the whole loop with a list comprehension or generator expression:

DIRECTORYT += [values[letter] for letter in DIRECTORY[0]]
DIRECTORYT += [values[letter] for letter in values if letter in DIRECTORY[0]]


DIRECTORYT.extend(values[letter] for letter in DIRECTORY[0])
DIRECTORYT.extend(values[letter] for letter in values if letter in DIRECTORY[0])

The advantage of the extend/generator expression versions is, again, that they don't build temporary lists.

share|improve this answer
It does not work, I keep getting a blank result when I have it print the Directory –  Owatch Feb 16 '13 at 17:32
@Owatch: Please show the code (somewhere like pastebin.com) and explain where you're "print[ing] the Directory". Multiple people have bent over backward trying to read your mind here, but apparently none of use are Professor X. –  abarnert Feb 18 '13 at 18:59
add comment

It's unclear to me everything you were trying to accomplish in your code, but here how to translate each the characters of the string entered into the values shown in your code. There's no need to convert to first convert it to a list because a string is already a sequence of letters, which can be treated just like items in a list in most cases (the main difference being that they can't be changed).

It uses a Python dictionary (or dict) to hold the translation because that allows it to be used to lookup each letter and find the value associated with it very quickly, usually much faster than searching for it by checking every entry in a regular table or list.

It also makes sure only alphabetic characters (letters) are translated and converts uppercase ones to lowercase for the look-up operation since the dictionary only has entries for them in it.

import string

translate = {
    'a': "0.01", 'b': "0.11", 'c': "1.11", 'd': "0.02", 'e': "0.22", 'f': "2.22",
    'g': "0.03", 'h': "0.33", 'i': "3.33", 'j': "0.04", 'k': "0.44", 'l': "4.44",
    'm': "0.05", 'n': "0.55", 'o': "5.55", 'p': "0.06", 'q': "0.66", 'r': "6.66",
    's': "0.07", 't': "0.77", 'u': "7.77", 'v': "0.08", 'w': "0.88", 'x': "8.88",
    'y': "0.09", 'z': "0.99",

print("\n\nPlease type in a string to be encrypted and press the Enter key")
entry = input("Entry: ")

directory = [translate[ch.lower()] for ch in entry if ch in string.ascii_letters]

print('directory:', directory)
share|improve this answer
input() if you are using Python 3.x, otherwise raw_input() –  Burhan Khalid Feb 16 '13 at 11:24
@BurhanKhalid: The OP is using input in his original code, and print as a function, etc., so hopefully he's using 3.x. But, considering his other comments, it's conceivable that he's using 2.x but following a 3.x tutorial, so that may be a useful comment after all… –  abarnert Feb 18 '13 at 19:04
@abarnert: I got the impression the OP was using 3.x, so tailored my answer accordingly -- never thought about the possibility you mentioned of them mixed-up. Oh, well, with no response so far, they don't seem concerned one way or the other. –  martineau Feb 18 '13 at 19:40
@martineau: Yeah, I got the same impression, which is why I started off by saying the "otherwise raw_input()" comment wasn't necessary… but then I realized he had a float where he expected a str in some unseen code that appears to call input –  abarnert Feb 18 '13 at 19:59
@martineau: Also, the OP has responded to the other two answers, basically saying "I tried some different code from the code you gave, and it doesn't work in some unspecified way", followed by adding "I've now got a new problem..." to his question. Maybe the "new problem" is that wolverines are eating his router, and that's why he hasn't answered again since then? –  abarnert Feb 18 '13 at 20:01
show 1 more comment

Your Answer


