好的,所以我做了很多研究,但我找不到任何答案,所以我来这里寻求帮助。
我遇到的问题是我无法获取变量,然后在我的代码后台将该变量的每个字符串转换回其ascii形式并使用数学操作它,例如+, - ,*和/。这是我的代码..
注意:我有一个理论,它使用for循环来说明这个变量中的每个字符,做......等等等等。不管怎样,这是我的代码。
import random
import sys
import time
invalid_input = True
def start():
print("Welcome to the Encryption / Decryption Program!")
menuAnswer = input("Please select the number corresponding to the option you would like (1 - 3)\n---------------------------------\n[1] Encrypt\n[2] Decrypt\n[3] Exit the program\n---------------------------------\n")
if menuAnswer == '1':
print("You have chosen to Encrypt!")
invalid_input = False
message = open("sample.txt","r")
msgName = input("What is the name of the text document you would like to Encrypt?\n")
msgName = msgName.upper()
if msgName == 'SAMPLE':
key = '' #This variable will have the encryption key stored inside of it.
for i in range(0,8):
random_number = (random.randint(33,162)) #Generate a random ascii number from the range 33 to 162
key +=str(chr(random_number)) #Convert and store this ascii number as a character to the variable 'Key'
print(key)
print("Remember this key, as you will need it to decrypt your file!")
#\\ Offset //# #Finding the offset, must be able to convert each individual character of the key variable and return it to its usual form to manipulate using math.
else:
print("Invalid Filename")
elif menuAnswer == '2':
print("You have chosen to Decrypt!")
invalid_input = False
elif menuAnswer == '3':
print("You have chosen to exit!")
invalid_input = False
time.sleep(1)
print("Exiting...")
time.sleep(1.5)
exit()
else:
print("Invalid Input, Please try again!")
while invalid_input:
start()
很抱歉,如果这个问题很难理解,我自己很困惑,并且已经坚持了一个星期。
答案 0 :(得分:0)
如果我理解正确你想要将字符串的每个字符转换为ascii数字,然后对其进行某种数学运算,然后将其转换回字符串,你可以使用ord()
这样做
s = 'Sample'
tmp = ''
for i in s:
tmp += chr(ord(i)+1)
print tmp
Tbnqmf
虽然使用代码你不需要将它转换为字符串,然后返回字符来操作它,你只需选择一个随机数就可以操作它
import random
def start():
key = ''
for i in range(0,8):
random_number = (random.randint(33,162))
key +=chr(random_number+1)
print(key)
start()
注意操作角色时需要小心,因为你可以将其操作为不是ascii字符的数字