擅长:python、mysql、java
<p>要解决间距问题,可以将<code>else</code>添加到<code>if ch.isalpha()</code>,只需将纯文本字符附加到密文中。这也将处理标点符号和其他特殊的非字母字符。你知道吗</p>
<p>要处理包装(例如X到A),您需要使用模运算符<code>%</code>。因为<code>A</code>是第65个ASCII字符,而不是第0个,所以您需要将alpha字符归零,然后应用mod,然后加回偏移量'A'。要使用环绕移位,可以执行如下操作:<code>final_letter = chr((ord(ch) + shift - ord('A')) % 26 + ord('A'))</code>。注意26来自拉丁字母表中的字母数。你知道吗</p>
<p>考虑到这些,下面是一个完整的示例:</p>
<pre><code>plain_text = input("Secret message: ")
shift = int(input("Shift: "))
def caesar(plain_text, shift):
cipher_text = ""
for ch in plain_text:
if ch.isalpha():
final_letter = chr((ord(ch) + shift - ord('A')) % 26 + ord('A'))
cipher_text += final_letter
else:
cipher_text += ch
print(cipher_text)
return cipher_text
caesar(plain_text, shift)
</code></pre>
<p>样本输入:</p>
<pre><code>plain_text = "THE IDES OF MARCH"
shift = 1
cipher_text = caesar(plain_text, shift)
print(cipher_text)
# UIF JEFT PG NBSDI
</code></pre>