TwoShorts
TwoShorts

Reputation: 548

Python: Changing values in a String with a for loop

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?

Upvotes: 0

Views: 3652

Answers (2)

Sanjar Stone
Sanjar Stone

Reputation: 904

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)

Upvotes: 0

user764357
user764357

Reputation:

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')]

Upvotes: 1

Related Questions