运行此代码时,它实际上并没有替换字符串...为什么?此外,这是否可行?

时间:2019-04-28 15:03:57

标签: python

抱歉,代码混乱。我真的没时间我是新手,只是在尝试。我只是想知道为什么不替换字符串。 如您所见,“ b64ed”和“ final_product”是相同的...

对不起。我很笨xD

import base64;
import time;
import os;
import random;
import string;
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast


enc_method = input("Would you like to manually input the text or load a .txt file? \n Press 1 for manual or 2 for importing: \n");


if enc_method == "1":
    filename = input("Enter the filename.txt: ");
    print("Importing String.... \n")
    with open(filename) as fn:
        toEnc_string = fn.read();
    print("String imported!");
    print(toEnc_string)

elif enc_method == "2":
    toEnc_string = input("Paste or Type the string you want to encrypt: \n");

else:
    print("For fucks sake...")


def oneS():
    return time.sleep(1)


def clearScreen():
    print("Clearing screen in 5...")
    time.sleep(1)
    print("4...")
    time.sleep(1)
    print("3...")
    time.sleep(1)
    print("2...")
    time.sleep(1)
    os.system("clear")

clearScreen()

def randomString(lenOfThatshit):
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for i in range(lenOfThatshit))

def bs64e(x):
    rummed = x.encode("utf-8")
    encoded = base64.b64encode(rummed)
    return encoded

print("You will now be asked to chose random Characters about 10 times. Choose differently each time.")
rs1 = input("Choose 6 random letters without spaces. Dont repeat: ")
rs2 = randomString(len(rs1))
#rs2 = input("Choose 6 more random letter without spaces. Dont repeat: ")

randStr = list(rs1)
randStr2 = list(rs2)

b64ed = str(bs64e(toEnc_string))

for i in range(6):
    final_product = b64ed.replace(str(randStr[i]) , str(randStr2[i]))
    print(str(randStr[i]) + "to " + str(randStr2[i]))

passes = open("the special random characters.txt", "w")
amount_written = passes.write(str(randStr) + "\n" + str(randStr2))

print(b64ed)
print("\n")
print(len(b64ed))
print("\n")
print(final_product)
print("\n")
print(len(final_product))
#print("Number of bytes written : " + str(amount_written))

passes.close()

同样,我知道代码真的很乱。而且还有许多进口未使用。原谅我。我也会考虑的。

1 个答案:

答案 0 :(得分:0)

您在这里遇到了逻辑错误,总是替换b64ed字符串中的字符,因此实际上只能替换最后一个替换字符。因此,只有在b64ed碰巧包含randStr[5]字符的情况下,您才能看到更改,否则final_product将会与b64ed完全相同。

部分代码应如下所示:

final_product = b64ed
for i in range(6):
    final_product = final_product.replace(str(randStr[i]) , str(randStr2[i]))
    print(str(randStr[i]) + " to " + str(randStr2[i]))