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''。 此外,我无法看到它如何在该范围内打印。我尝试寻找解决方案,但那些包含的代码与我的相似。任何人都有我的问题的提示,
答案 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='')