简体   繁体   English

Python如何将字符转换为字符串

[英]Python how to convert character to string

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)
    
    
   

as you can see from the code above my code worked fine but the only problem that I am facing is I need to encrypt the message as string like I want to use " hello world" not only a character "s" and its encrypted to " d" i want "hello word"正如您从上面的代码中看到的,我的代码运行良好,但我面临的唯一问题是我需要将消息加密为字符串,就像我想使用“hello world”一样,而不仅仅是一个字符“s”,并将其加密为“ d”我想要“你好词”

I tried to correct your code:我试图更正您的代码:

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)

From what I understood, you are trying to encrypt your message by shifting the index using an affine function (and applying a modulo so it "loops" if the index is bigger than your alphabet size).据我了解,您正试图通过使用仿射函数移动索引来加密您的消息(并应用模数,以便在索引大于您的字母大小时“循环”)。 Since your input can contain multiple times the same char, you need to iterate through the input and then check for the index of every char in your alphabet (array).由于您的输入可以包含多次相同的字符,因此您需要遍历输入,然后检查字母表(数组)中每个字符的索引。 Then you can apply your formula to the index and get the new char.然后,您可以将公式应用于索引并获取新字符。 I also added a code to add the unciphered char if it doesn't exist in your array.如果数组中不存在未加密的字符,我还添加了一个代码来添加它。 This will prevent you to lose informations when ciphering.这将防止您在加密时丢失信息。 eg: hello world will be ciphered in xirrm tmars instead of xirrmtmars which couldn't be unciphered to get the original.例如: hello world将被加密xirrm tmars代替xirrmtmars这不可能是不加密来获得原始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM