运行此代码时,它实际上并不替换字符串...为什么?还有,这会变得实用吗?

问题描述 投票:-5回答:1

对不起凌乱的代码。我没有时间。我是新人,只是在尝试。我只想知道为什么弦不会被替换。如您所见,“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()

我知道,代码真的很混乱。还有很多未使用的进口产品。原谅我。我也会接受任何想法。

python
1个回答
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]))
© www.soinside.com 2019 - 2024. All rights reserved.