List item position

Python bootcamp #100DaysOfCode #myNotes

Today's final project was to build a Caesar Cipher program. Caesar Cipher is an very old encryption technique where each letter in 'readable text' is replaced by another letter determined by a fixed shift number. For example: If you want to encrypt the text 'hello' and the 'secret' shift number is 5, then the encrypted text would be 'mjqqt'. Every letter shifts 5 letters in the alphabet. 'h' becomes 'm' when shifted 5 letters and so on.
If the receiver of the text knows the secret shift number, they can shift the letters back and read the actual message.

If we want to do this in Python, we need to know the exact position (index) of the letter in the alphabet. I created a List called alphabet.

alphabet = ['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']

In Python, the first item in the list, is in position(index) 0. In the List alphabet the letter 'a' is in position 0, 'b' is in 1 etc. Taking the example of 'hello', and the secret shift number is 5, we want to know what the letters are after shifting them 5 positions individually. So we need to know the position of the letters so that we can replace them with the new letters. Taking the first letter 'h', getting the index of this letter (list item) is done by the list.index() method.

position = alphabet.index("h")

This wil return the position of the list item 'h' and will store it in the variable position. The index for 'h' is 7. (remember the index starts at 0).
Now that we know the index of 'h' we can shift it in the alphabet to get our encrypted letter. We shift it with a 'secret' shift number, in our example that number is 5. The new letter is 'm'

Here a little piece of today's final project where we needed to know the index of a list item.

def caesar(start_text, shift_amount, cipher_direction):
  end_text = ""
  if cipher_direction == "decode":
    shift_amount *= -1
  for char in start_text:
    #keep the number/symbol/space when the text is encoded/decoded.
    if char not in alphabet:
        end_text += char
    else:
        position = alphabet.index(char)
        new_position = position + shift_amount
        end_text += alphabet[new_position]

  print(f"Here's the {cipher_direction}d result: {end_text}")

Also good to know, the list.index() method returns the first position in the list with the given value. If the value has duplicate positions in the list, it always returns the first position.

names = ['James', 'Lucia', 'Effi', 'Jan', 'Lucia', 'Marco']
position = names.index("Lucia")
#position is 1, even though there is another "Lucia" in the list at postion 4.

More from Lucia
All posts