Python不会在字符串中添加字符串,即使我正确使用它也不会出错

时间:2017-10-30 20:21:02

标签: python string python-3.x

所以基本上我正在制作一个使用Vigenère广场的加密器,但由于某种原因,Python只成功存储了消息的第一个字母,然后当它执行命令并加密每个字符时它不会在消息中添加它们变量:

message=str()
keyword="ΒΑΡΕΘΗΚΑ"
string="ΑΝΚΑΤΑΦΕΡΕΣΝΑ"

charNum=[913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 937]
charTable={ "Α" : 0, "Β" : 1, "Γ" : 2, "Δ" : 3, "Ε" : 4, "Ζ" : 5, "Η" : 6, "Θ" : 7, "Ι" : 8, "Κ" : 9, "Λ" : 10, "Μ" : 11, "Ν" : 12, "Ξ" : 13, "Ο" : 14, "Π" : 15, "Ρ" : 16, "Σ" : 17, "Τ" : 18, "Υ" : 19, "Φ" : 20, "Χ" : 21, "Ψ" : 22, "Ω" : 23}


i=0
for char in string:
    character=charTable[char] + charTable[keyword[i]]
    if character > 23:
        character -= 24
    message += chr(charNum[character])
    print(message)

    i+=1
    if i==len(keyword):
        i=0

输出:

Β
Β
Β
Β
Β
Β
Β
Β
Β
Β
Β
Β
Β

每当它添加一个字母时,应该显示该消息。

如果我改变了

print(message)

print(chr(charNum[character]))

输出是这样的:

Β
Ν
Β
Ε
Β
Η
Ζ
Ε
Σ
Ε
Κ
Ρ
Θ

每个正确加密的字母。 发生了什么事?

1 个答案:

答案 0 :(得分:0)

从for循环中取出print(消息)并将其放在最后:

message=str()
keyword="ΒΑΡΕΘΗΚΑ"
string="ΑΝΚΑΤΑΦΕΡΕΣΝΑ"

charNum=[913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 937]
charTable={ "Α" : 0, "Β" : 1, "Γ" : 2, "Δ" : 3, "Ε" : 4, "Ζ" : 5, "Η" : 6, "Θ" : 7, "Ι" : 8, "Κ" : 9, "Λ" : 10, "Μ" : 11, "Ν" : 12, "Ξ" : 13, "Ο" : 14, "Π" : 15, "Ρ" : 16, "Σ" : 17, "Τ" : 18, "Υ" : 19, "Φ" : 20, "Χ" : 21, "Ψ" : 22, "Ω" : 23}

i=0
for char in string:
    character=charTable[char] + charTable[keyword[i]]
    if character > 23:
        character -= 24
    message += chr(charNum[character])
    i+=1
    if i==len(keyword):
        i=0
print(message)