gpt4 book ai didi

python - 凯撒密码 仅加密一个字母而不是整个字符串

转载 作者:行者123 更新时间:2023-11-30 22:06:35 24 4
gpt4 key购买 nike

所以我正在制作一个简单的凯撒密码用于练习,但我无法让它破译整个字符串,只能破译单个字母。

symbol_add 是有问题的函数。

代码如下:

import re

alphabet = "abcdefghijklmnopqrstuvwxyz"

def cleanIt(clean):
global alphabet
s = re.sub('[^a-z]+', '?', str(clean))
return s

def symbol_add(symbol, key):
encryptedMsg = ""
for x in symbol:
position = alphabet.find(x)
newPosition = (position + key) % 26
newLetter = alphabet[nyPosisjon]

encryptedMsg += nyBokstav
return encryptedMsg

def cipher(data,key):
text = ""
if data in alphabet:
text += symbol_add(symbol=data,key=key)
return text

def main():
try:
msg = (input("Write the message you would like to encrypt\n"))
key = int(input("which key would you like to use?\n"))
cleanIt(clean=msg)
print(cipher(data=msg, key=key))
except ValueError:
print("Write a number!")

main()

我确信解决方案非常简单,仍在学习中。

任何有关如何解决此问题的帮助将不胜感激!

最佳答案

import re

alphabet = "abcdefghijklmnopqrstuvwxyz"

def cleanIt(clean):
global alphabet
s = re.sub('[^a-z]+', '?', str(clean))
return s

def symbol_add(symbol, key):
position = alphabet.find(symbol)
newPosition = (position + key) % 26
newLetter = alphabet[newPosition]
return newLetter

def cipher(data,key):
text = ""
for letter in data:
if letter in alphabet:
text += symbol_add(symbol=letter,key=key)
return text

def main():
try:
msg = (input("Write the message you would like to encrypt\n"))
key = int(input("which key would you like to use?\n"))
# Note: you need to assign msg to be equal to cleanIt(clean=msg).
# Just calling cleanIt(clean=msg) won't work, as strings
# are immutable in Python
msg = cleanIt(clean=msg)
print(cipher(data=msg, key=key))
except ValueError:
print("Write a number!")

main()

主要变化是:

  • for loop已移自 symbol_addcipher ,这样symbol_add每个角色都会被调用
  • main() :cleanIt(clean=msg) -> msg = cleanIt(clean=msg) ;原因是Python中的字符串是不可变的,这意味着你需要重新分配变量msg实质上指向新字符串。

此代码的输出:

Write the message you would like to encrypt
test
which key would you like to use?
1
uftu

此外,尝试坚持单一命名约定;你有一个遵循 camelCase 的函数( cleanIt ) 以及随后的另一个 snake_case (symbol_add)。尝试以相同的方式命名所有函数。 (Python 中的约定是使用 snake_case 表示函数)

关于python - 凯撒密码 仅加密一个字母而不是整个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52682436/

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