python - 如何通过字符串获取 chr 的代码?
问题描述
我正在编写用于密码的代码。查看我的代码时,您可以看到该 defxor()
代码,但我需要它来处理字符串中的多个字母,但它一直说它不能这样做,因为有多个字母在执行该chr
功能。
if __name__=="__main__":
#After the string to decode is input, the user needs to input a word that will or will not be in the string.
stringtodecode = input("Message to Decode: ")
key = input("Key Word: ")
def encrypt(stringtodecode, key):
encrypted = ''
for character in stringtodecode:
encrypted = encrypted + xor(character, key)
return encrypted
def decrypt(stringtodecode, key):
return encrypt(stringtodecode, key)
def xor(character, key):
code = ord(character) ^ ord(key)
character = chr(code)
return character
print(decrypt(stringtodecode, key))
我得到一个TypeError
.
解决方案
如果要循环关键字的字符,可以使用itertools.cycle
andzip
将其作为循环消息中字符的一部分:
import itertools # put this up near the top of the file somewhere
for m_char, k_char in zip(stringtodecode, itertools.cycle(key)):
encrypted = encrypted + xor(m_char, k_char)
如果字符串可能变长(它所花费的时间与输出长度的平方成正比),通过重复连接构建字符串将是低效的,因此您可能希望str.join
在生成器表达式上使用(它将以线性时间运行):
encrypted = "".join(xor(m_char, k_char)
for m_char, k_char in zip(stringtodecode, itertools.cycle(key)))
推荐阅读
- php - 试图在laravel中获取非对象的属性“状态”
- powershell - 格式化来自 docker 事件的 json 输出
- javascript - 如何仅禁用上个月的日期
- android - 如何解决重复的 gradle 依赖项(jsr305)?
- list - 如何检查1000s目录中的配对文件
- performance - VUE/NUXT SSR 在不重新加载的情况下将查询字符串添加到 URL - 性能问题和缓慢的滚动
- java - ActiveMQ 持久消费者在删除主题后保留其订阅
- bash - 从shell中带有空格的变量打开目录
- python-3.x - 当我训练我的 LSTM 模型时,我的损失显示为 NaN,准确率为 0
- spring-boot - PayPal OAuth 2.0 设置