gpt4 book ai didi

python - 回到字符串的开头

转载 作者:太空宇宙 更新时间:2023-11-04 10:00:25 26 4
gpt4 key购买 nike

我正在编写凯撒密码。 key 是从 1 到 25 的整数。此密码轮换字母表中的字母(A 到 Z)。编码替换每个字母字母表中的第 1 到第 25 个下一个字母(将 Z 包装到 A)。因此 key 2 将“HI”加密为“JK”,而 key 20 将“HI”加密为“BC”。

但是如果我输入“我 super ”它会输出“k kc oouwrgt”,而它应该是“k co uwrgt”,键为 2。它也不会回到字母表的开头,例如“x”不会转到“a” ' 键为 2。我使用 python 3.4.1

encode = []
a = "abcdefghijklmnopqrstuvwyxz"
a = list(a)
print(a)

e = input("encode or decode --->")
text = input("Sentence -->").lower()
text = list(text)
print(text)


Key = int(input("Key -->"))
if Key > 25:
print("Too high")
else:
print(Key)

if e == "encode":
for i, item in enumerate(text):
if item == " ":
encode.append(letter)
else:
num = a.index(item)
num = num + int(Key)
letter = a[num]
encode.append(letter)

for i in range(len(encode)):
print(encode[i])

最佳答案

遇到空格时,再次追加最后一个字母,而不是item:

if item == " ":
encode.append(letter)

当键为2时,这会导致ko出现两次;您重新附加了编码的 i -> km -> o 结果。

您需要使用 % modulo operator使您的索引“环绕”:

num = (num + Key) % 26

我删除了 int() 调用,您之前已经将 Key 转换为整数。

其他提示:

  • 你不需要把a变成一个列表;字符串也是序列,直接支持索引和 .index() 方法。这同样适用于文本;只需遍历字符串本身。

  • 您没有在 for i, item in enumerate(text): 循环中使用 i;完全删除 enumerate:for item in text:

  • 可以直接在该循环中打印编码字符,无需使用encode 列表和单独的循环。

    <
  • str.join() method会让您在一行中打印所有编码文本:print(''.join(encode)) 而不是最后一个 for 循环。

  • 绝对最快的字符串编码方法是使用翻译表,将输入字符映射到输出字符的字典,以及str.translate() method .您可以使用 str.maketrans() function制作那张 table :

    import string

    a = string.ascii_lowercase # why type yourself when the stdlib has these?
    text = input("Sentence -->").lower()
    Key = int(input("Key -->"))
    mapping = str.maketrans(a, a[Key:] + a[:Key]) # letters to rotated letters
    print(text.translate(mapping))

    诀窍在于为 str.maketrans() 创建第二个字符串;使用切片可以很容易地创建一个旋转字符串,方法是从 Key 位置开始获取所有内容,最后是第一个 Key 字符:

    >>> a[Key:] + a[:Key]
    'cdefghijklmnopqrstuvwyxzab'

关于python - 回到字符串的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43843330/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com