Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
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

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)
 
Share this answer
 
v2
Comments
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. :-)
Strings are immutable in Python, so you can't remove and insert characters.
Instead, do it like this:
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900