如何在Python(2.7)中使Caesar解码器循环?

2024-09-30 10:30:34 发布

您现在位置:Python中文网/ 问答频道 /正文

在经历了很多挫折之后,我制作了我的第一个凯撒解码器:)

但现在的问题是让程序循环。。。在

例如,如果我们想doge移动1,没问题,它是ephf。。。在

但是xyz,而移位是4???在

所以编程专业人士帮助第一次新手,也就是新手:p 谢谢。。。在

import string
def main():        
    inString = raw_input("Please enter the word to be "
                         "translated: ")
    key = int(raw_input("What is the key value? "))

    toConv = [ord(i) for i in inString] #now want to shift it by key
    toConv = [x+key for x in toConv]
    #^can use map(lambda x:x+key, toConv)
    result = ''.join(chr(i) for i in toConv)

    print "This is the final result due to the shift", result

Tags: thetokeyinforinputrawshift
3条回答

只需将key添加到所有实际的字符代码中,那么如果增加的值大于z,则使用字符代码z进行模运算,并将其与字符代码a相加。在

inString, key = "xyz", 4
toConv = [(ord(i) + key) for i in inString] #now want to shift it by key
toConv = [(x % ord("z")) + ord("a") if x > ord("z") else x for x in toConv]
result = ''.join(chr(i) for i in toConv)
print result   # cde

我建议使用^{}。在

因此,我们可以做以下工作:

key = 1
table = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase[key:] + string.ascii_lowercase[:key] + string.ascii_uppercase[key:] + string.ascii_uppercase[:key])

然后我们可以使用它如下:

^{pr2}$

特别是,这不会更改非ascii小写或大写字符的字符,如数字或空格。在

'3 2 1 a'.translate(table) # Outputs '3 2 1 b'

一般来说,要使某个东西“包装”,您需要使用模函数(%,在Python中)和要包装的数字和范围。例如,如果我想把数字1到10打印一次,我会这样做:

i = 0
while 1:
    print(i%10+1)
    # I want to see 1-10, and i=10 will give me 0 (10%10==0), so i%10+1!
    i += 1

在本例中,这有点困难,因为您使用的是ord,它没有一个很好的“范围”值。如果你做过类似string.ascii_lowercase的事情,你可以。。。在

^{pr2}$

但是,由于您使用的是ord,我们有点从ord('A') == 65到{},因此范围为0->;57(例如range(58),常数为65)。换句话说:

codex = "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz"
# every char for chr(65) -> chr(122)

codex = ''.join([chr(i+65) for i in range(58)]) # this is the same thing!

我们可以改为这样做,但它将包含字符[\]^\

inString, key = 'abcxyzABCXYZ', 4
toConv = [(ord(i)+key-65)%58 for i in inString]
result = ''.join(chr(i+65) for i in toConv)
print(result)
# "efgBCDEFG\\]^"

相关问题 更多 >

    热门问题