0

I am trying to build a caesar cipher in python, so I am trying to loop through the string and change the characters.

def caesar_shift(s, n):
  letters = list(s)
  for x in letters:
      if x == ' ':
          continue
      x = ord(x)
      x += n
      while (97 < x < 122) != True:
        if x < 97:
          x += 26
        elif x > 122:
          x -= 26
  letters = ''.join(letters)  
  return letters
print caesar_shift('a',1)

My output shows that x changes to 98, then turns into a 'b', but when the actual string is printed, all it shows is the letter 'a'. Any help?

2 Answers 2

1

x is a local variable within the loop and isn't changing the value of the element in the array.

You need to assign the new value of x back into the array like so:

for i,x in enumerate(letters):
    # ... rest of your loop
    letters[i] = x

From the Python documentation for the enumerate() function:

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Sign up to request clarification or add additional context in comments.

2 Comments

Wow thanks so much! Could you explain how this works with the enumerate?
@user2909227 Linked and added the documentation for enumerate.
0

Try this code:

#!/usr/bin/python
def encrypt(s,n):
  letters=list(s)
  cipher=[]
  for x in letters:
    if x==' ':
      continue
    else:
      p=ord(x)+n
      if(p>122):
        p=p-25
      cipher.append(chr(p))
  return cipher
print encrypt('abcde',1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.