wongy1995
wongy1995

Reputation: 1

how do i make a ceaser cipher where the letter "z" becomes "a" on +1 shift in python

How do I shift the end of the alphabet so "z" becomes "a"?

i was thinking a if statement

plaintext = input("please type message:")

def split(plaintext):
    return list(plaintext)
print(split(plaintext))

for s in plaintext:
    a = ord(s)
    print (a)
list1=[]
for t in plaintext:
    b = ord(t)
    c = b+1
    print (c)
    list1.append(c)
print (list1)
aa =""
for ab in list1:
    aa = aa + chr(ab)
print (str(aa))
print(split(aa))

Upvotes: 0

Views: 37

Answers (2)

hiro protagonist
hiro protagonist

Reputation: 46849

if you just want to increase the character by one you could do this:

def inc_chr(c):
    return chr((ord(c) + 1 - ord("a")) % 26 + ord("a"))

test:

for char in "abcxyz":
    print(f"{char} {inc_chr(char)}")

outputs:

a b
b c
c d
x y
y z
z a

basically you do calculations modulo 26 with an offset of ord("a") = 97.

Upvotes: 1

Ritwik G
Ritwik G

Reputation: 416

You can use a look up dict and convert the characters.

import string
alphabets = string.ascii_lowercase
look_up = {alphabets[i]: alphabets[i-1] for i in range(len(alphabets))}

You can then use this lookup for cypher

test = "This will be encoded"
out = = "".join([look_up.get(char, char) for char in test])
print(out)

Upvotes: 0

Related Questions