python 使用python的凯撒密码,可以使用一些帮助
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1538935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Caesar's Cipher using python, could use a little help
提问by Neil Vass
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)
我正在尝试在使用 python 时制作“凯撒密码”..这是我到目前为止所拥有的。谁能告诉我这是怎么看的?我是否朝着正确的方向前进?我错过了什么?例如,当我运行程序时(josh 很酷),我没有在同一行得到密码。当我这样做时看起来像这样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),
回答by Neil Vass
I like kaizer.se's answer, but I think I can simplify it using the string.maketransfunction:
我喜欢 kaizer.se 的答案,但我想我可以使用string.maketrans函数来简化它:
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)
回答by Jeff B
This code should work pretty well. It also handles arbitrary offsets, including negative.
这段代码应该工作得很好。它还处理任意偏移量,包括负数。
phrase = raw_input("Please enter plaintext to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ''
for char in phrase:
x = ord(char)
if char.isalpha():
x = x + shift
offset = 65
if char.islower():
offset = 97
while x < offset:
x += 26
while x > offset+25:
x -= 26
result += chr(x)
print result
The other way to do it, with a slightly different cipher, is simply rotate through all characters, upper and lower, or even all ascii > 0x20.
另一种方法是使用略有不同的密码,只需旋转所有字符,上下,甚至所有 ascii > 0x20。
phrase = raw_input("Please enter plaintext to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ''
for char in phrase:
x = ord(char)
x = x + shift
while x < 32:
x += 96
while x > 127:
x -= 96
result += chr(x)
print result
回答by u0b34a0f6ae
Here is a different method to show how we can handle this in a very clean way. We define an input alphabet and an output alphabet, then a translation table and use unicode.translate()
to do the actual encryption.
这是一种不同的方法来展示我们如何以非常干净的方式处理这个问题。我们定义了一个输入字母表和一个输出字母表,然后是一个转换表并用于unicode.translate()
进行实际的加密。
import string
# Blatantly steal Lennart's UI design
first = unicode(raw_input("Please enter Plaintext to Cipher: "), "UTF-8")
k = int(raw_input("Please enter the shift: "))
in_alphabet = unicode(string.ascii_lowercase)
out_alphabet = in_alphabet[k:] + in_alphabet[:k]
translation_table = dict((ord(ic), oc) for ic, oc in zip(in_alphabet, out_alphabet))
print first.translate(translation_table)
It can be extended to uppercase letters as needed.
可以根据需要扩展为大写字母。
回答by Mark Ransom
Put a comma after each print statement; it will still put a space between the characters, but they'll all be on the same line. If you need to print them without the spaces, build them all into a single string and print that at the end.
在每个打印语句后放置一个逗号;它仍然会在字符之间放置一个空格,但它们都将在同一行上。如果您需要在没有空格的情况下打印它们,请将它们全部构建为一个字符串并在最后打印。
回答by Lennart Regebro
Barring the syntax errors, your code seems to work.
除非出现语法错误,否则您的代码似乎可以正常工作。
However, I took the liberty of removing all duplicates, and cleaning it up:
但是,我冒昧地删除了所有重复项并进行了清理:
first = raw_input("Please enter Plaintext to Cipher: ")
k = int(raw_input("Please enter the shift: "))
result = ''
for second in first:
x=ord(second)
x=x+k
if x>90 and x<122:
x=x-26
elif x>122:
x=x-26
result += chr(x)
print first
print result
Also "first" and "second" are really bad names for those variables. "Input" and "letter" is probably better.
对于这些变量来说,“first”和“second”也是非常糟糕的名字。“输入”和“字母”可能更好。
回答by dorvak
I very simple, 3-shift solution without Umlauts and alike would be:
我很简单,没有变音等的 3 班制解决方案是:
def caesar(inputstring):
shifted=string.lowercase[3:]+string.lowercase[:3]
return "".join(shifted[string.lowercase.index(letter)] for letter in inputstring)
and reverse:
并反转:
def brutus(inputstring):
shifted=string.lowercase[-3:]+string.lowercase[:-3]
return "".join(shifted[string.lowercase.index(letter)] for letter in inputstring)
using it:
使用它:
caesar("xerxes")
回答by user2997187
For Python 3.3, try using the ord(), chr() and .isalpha functions:
对于 Python 3.3,尝试使用 ord()、chr() 和 .isalpha 函数:
m = input("What is your message?: ")
s = int(input("What is the shift?: "))
for i in m:
if i.isalpha():
if (ord(i)+s)>90:
print(chr(ord(i)+s-26),end=""),
elif chr(ord(i)+s-26)<65:
print("The shift is invalid")
else:
print(chr(ord(i)+s),end=""),
else:
pass
回答by thekindlyone
Here is a oneliner.
这是一个单线。
>>> brutus=lambda message,cipher,direction:''.join([chr((ord(letter)+(cipher*direction))%256) for letter in message])
>>> encrypted= brutus('Message to be encrypted',14,1) #direction=1 for encryption
>>> encrypted
'[s\x81\x81ous.\x82}.ps.s|q\x80\x87~\x82sr'
>>> brutus(encrypted,14,-1) # direction=-1 for decryption
'Message to be encrypted'
>>>