首页 > 解决方案 > Python如何将字符转换为字符串

问题描述

array = "qwertyuiopasdfghjklzxcvbnm"

m = len(array)
user_input= input("Enter plaintext: ")
a= int(input("choose a: "))
b= int(input("choose b: "))

encryption = ""
for n in array:

   if n in user_input :
    
    inin=array.find(n)
    result =array.index(user_input) * a+b
    enc= result % m
    encryption = encryption + array[enc]
    
    
    
    
   
 print("Encrypted message is :"+encryption)
    
    
   

正如您从上面的代码中看到的那样,我的代码运行良好,但我面临的唯一问题是我需要将消息加密为字符串,就像我想使用“hello world”一样,不仅是一个字符“s”,而且它加密为“ d" 我想要"你好词"

标签: pythonstring

解决方案


我试图更正您的代码:

array = "qwertyuiopasdfghjklzxcvbnm"

m = len(array)
user_input= input("Enter plaintext: ")
a= int(input("choose a: "))
b= int(input("choose b: "))

encryption = ""
for char in user_input:
   if char in array :
    index = (array.find(char) * a + b) % m
    encryption += array[index]
   else:
    encryption += char

print("Encrypted message is :", encryption)

据我了解,您正试图通过使用仿射函数移动索引来加密您的消息(并应用模数,因此如果索引大于您的字母表大小,它会“循环”)。由于您的输入可以包含多次相同的字符,因此您需要遍历输入,然后检查字母表(数组)中每个字符的索引。然后您可以将公式应用于索引并获取新字符。如果您的数组中不存在未加密的字符,我还添加了一个代码来添加它。这将防止您在加密时丢失信息。例如:hello world将被加密,xirrm tmars而不是xirrmtmars无法解密以获取原件。


推荐阅读