14,875,846 members
1.00/5 (1 vote)
See more:
Let the given string be “Python” and the key is 3 letters away from each letter of the alphabet
So “python” becomes “sbwkrq”

What I have tried:

Python
```x=input()
for i in range(0,len(x)):
if x[i]=='x':
x.remove('x')
x.insert(i,'a')
if x[i]=='y':
x.remove('y')
x.insert(i,'b')
if x[i]=='z':
x.remove('z')
x.insert(i,'c')
else:
x.del('x[i]')
x.insert(i,chr(ord(x[i]+1)))
print(x)```
Posted
Updated 8-Nov-20 21:12pm
v2

## Solution 1

Just add `3` to `ord(x[i])` and then check (and adjust) the out-of-range cases:
Python
```x = input()
y = ''
for i in range(0,len(x)):
c = ord(x[i]) + 3
if c > ord('z'):
c = c - ord('z') + ord('a') - 1
y = y + chr(c)

print(y)```

You can also do that using a one-liner expression
Python
```x = input()
y = ''.join((chr((ord(l)-ord('a') + 3) % 26 + ord('a'))) for l in x)
print(y)```
v2
Richard MacCutchan 9-Nov-20 4:13am

Don't forget the upper case letters.
CPallini 9-Nov-20 4:16am

That is left as an exercise. :-)

## Solution 2

Strings are immutable in Python, so you can't remove and insert characters.
Python
```result = ''
offset = 3
for i in range(0,len(x)):
val = ord(x[i]) + offset
if val > ord('z'):
val = val - 26
result = result + chr(val)
print(result)```
Using a variable to hold your offset means that your Caesar Cypher becomes more flexible, comparing to the last valid value means the wrap works regardless of the value of `offset`, provided it is positive.