Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

Caesar's Cipher using python, could use a little help

I'm trying to make a "Caesar's Cipher" while using python..this is what I have so far. Could anyone tell me how this is looking? Am I going in the right direction? What am I missing? When I run the program to say for example (josh is cool) I don't get the cipher on the same line. It looks like this when I do main(3)

m
r
v
k
l
v
f
r
r
o

But it puts each letter on a new line. How could I do it so that it is on one line?

def main(k):

    if k<0 or k>231:
        print "complaint"
        raise SystemExit

    Input = raw_input("Please enter Plaintext to Cipher")

    for x in range(len(Input)):
        letter=Input[x]
        if letter.islower():
            x=ord(letter)
            x=x+k
            if x>122:
                x=x-122+97
            print chr(x),
        if letter.isupper():
            x=ord(letter)
            x=x+k
            if x>90:
                x=x-90+65
            print chr(x),
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I like kaizer.se's answer, but I think I can simplify it using the string.maketrans function:

import string

first = raw_input("Please enter Plaintext to Cipher: ")
k = int(raw_input("Please enter the shift: "))

shifted_lowercase = ascii_lowercase[k:] + ascii_lowercase[:k]

translation_table = maketrans(ascii_lowercase, shifted_lowercase)

print first.translate(translation_table)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...