Skip to content
Advertisement

How can I reference a string (e.g. ‘A’) to the index of a larger list (e.g. [‘A’, ‘B’, ‘C’, ‘D’, …])?

I have been racking my brain and scouring the internet for some hours now, please help. Effectively I am trying to create a self-contained function (in python) for producing a caesar cipher. I have a list – ‘cache’ – of all letters A-Z.

def caesarcipher(text, s):
    global rawmessage  #imports a string input - the 'raw message' which is to be encrypted.
    result = ''
    cache = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
         'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

Is it possible to analyze the string input (the ‘rawmessage’) and attribute each letter to its subsequent index position in the list ‘cache’? e.g. if the input was ‘AAA’ then the console would recognise it as [0,0,0] in the list ‘cache’. Or if the input was ‘ABC’ then the console would recognise it as [0,1,2] in the list ‘cache’.

Thank you to anyone who makes the effort to help me out here.

Advertisement

Answer

Use a list comprehension:

positions = [cache.index(letter) for letter in rawmessage if letter in cache]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement