Python 3.63,Vigenere cypher打印超出范围

时间:2017-11-30 12:40:28

标签: python-3.x range newline vigenere

第一个问题!我在尝试之前尝试寻找答案,但除了完全其他代码之外我找不到任何其他代码......:\  我的代码如下:

import sys

if len(sys.argv) != 2:
    print("usage: python vigenere.py key")
    exit(1)

key = (sys.argv[1])
s = input("plaintext: ")
j = 0
for i in range(len(s)):
    # so that j wraps around
    j = j % len(key)
    for j in range(len(key)):
        # check for every j in key if it is upper, or lowercase
        if ord(key[j]) >= ord("A") and ord(key[j]) <= ord("Z"):
            j -= 65
        elif ord(key[j]) >= ord("a") and ord(key[j]) <= ord("z"):
            j -= 97
        # for every capital letter, print out the encyphered letter
        if ord(s[i]) >= ord("A") and ord(s[i]) <= ord("Z"):
            print("1{}".format(chr((ord(s[i]) + j - 65) % 26 + 65), end=''))

        # same for every non capital
        elif ord(s[i]) >= ord("a") and ord(s[i]) <= ord("z"):
            print("2{}".format(chr((ord(s[i]) + j - 97) % 26 + 97), end=''))

        # if it is not capital, print it out
        else:
            print("3{}".format(s[i]), end='')

它是一个vigenere cypher,它应该带一个密钥,一个明文和encypher带密钥的明文。我跑的时候:

>python vigenere.py abc

plaintext: abc

I get:

2h

2i

2j

2i

2j

2k

2j

2k

2l

(我把1,2和3放在那里,这样我就可以看出资本和非资本是否有效。)

所以我的问题是,新行来自哪里?我在每次打印后都把= end''。 此外,我无法看到它如何在该范围内打印。我尝试寻找解决方案,但那些包含的代码与我的相似。任何人都有我的问题的提示,

1 个答案:

答案 0 :(得分:1)

移动括号,代码end=''用于format函数:

print("1{}".format(chr((ord(s[i]) + j - 65) % 26 + 65), end=''))

print("1{}".format(chr((ord(s[i]) + j - 65) % 26 + 65)), end='')
在第二个for http://rextester.com/VOVSP83705

之后

和dedent

import sys


key = "key"
s = "abc"

j = 0
for i in range(len(s)):    
    # so that j wraps around
    j = j % len(key)
    for j in range(len(key)):
        # check for every j in key if it is upper, or lowercase
        if ord(key[j]) >= ord("A") and ord(key[j]) <= ord("Z"):
            j -= 65
        elif ord(key[j]) >= ord("a") and ord(key[j]) <= ord("z"):
            j -= 97
    # for every capital letter, print out the encyphered letter
    if ord(s[i]) >= ord("A") and ord(s[i]) <= ord("Z"):
        print("{}".format(chr((ord(s[i]) + j - 65) % 26 + 65)), end='')            

    # same for every non capital
    elif ord(s[i]) >= ord("a") and ord(s[i]) <= ord("z"):
       print("{}".format(chr((ord(s[i]) + j - 97) % 26 + 97)), end='')

    # if it is not capital, print it out
    else:
        print("{}".format(s[i]), end='')