追加和替换一个字符串中的对象

我正在编写一个文本编码器/加密器(全部由我自己),但我不明白如何在字符串中附加和替换字符:-/

代码:


import os, sys, random


dig = 0

text_encoded = ""

text = ""


try:

    if os.path.isfile(sys.argv[1]) == True:

        with open(sys.argv[1], "r") as text:

            text = text.readlines()

except:

    pass


if text == "":

    print("Write the text to encode")

    text = input()


text = text.split()


for _ in range(len(text)):

    text_encoded = text[dig].replace("qwertyuiopasdfghjklzxcvbnm ", "mnbvcxzlkjhgfdsapoiuytrewq@")

    dig = dig+1


print("Your encoded text is:\n"+text_encoded)

这是一些输出:


Write the text to encode

lo lolo lol lol

Your encoded text is:

lol

如果你能以任何方式帮助我,谢谢:-)


阿晨1998
浏览 166回答 3
3回答

MYYA

如果我没听错,你想用 m 替换 q,用 n 替换 w 等等。尝试以下import os, sys, randomdig = 0text_encoded = ""text = ""try:    if os.path.isfile(sys.argv[1]) == True:        with open(sys.argv[1], "r") as text:            text = text.readlines()except:    passif text == "":    print("Write the text to encode")    text = input()mychars=list("qwertyuiopasdfghjklzxcvbnm ")myencode=list("mnbvcxzlkjhgfdsapoiuytrewq@")charmap=zip(mychars,myencode)_map = dict(charmap)encoded_text = ''.join(_map.get(c) for c in text)print("Your encoded text is:\n"+encoded_text)您问题中的字符串提到您想用@替换''。如果您不想这样做,只需从上述两个字符串中删除最后一个字符。

拉风的咖菲猫

或者你可以使用str.translateimport os, sys, randomfrom pathlib import PathTEXT_MAP = ("qwertyuiopasdfghjklzxcvbnm ", "mnbvcxzlkjhgfdsapoiuytrewq@")def main():    text = ''    if len(sys.argv) > 1:        fname = sys.argv[1]        p = Path(fname)        if p.is_file():            text = p.read_text().strip()            print(f'Text from {p} is: {text}')    if not text:        text = input("Write the text to encode: ").strip()    trantab = str.maketrans(*TEXT_MAP)    text_encoded = text.translate(trantab)    print("Your encoded text is:\n"+text_encoded)if __name__ == '__main__':    main()

慕侠2389804

有两个列表而不是字符串,例如 from_ = "abc".split() 和 to_ = "def".split() 在 from_ 中查找您的字符并获取索引,从 to_ 获取相同的索引字符并将其拼接到一个新的句子。example:from_ = "abc".split()to_ = "def".split()old_msg = "ab ab"new_msg = ""for each in old_msg.split():    new_msg = new_msg + to_[from_.index(each)]希望这会有所帮助,请添加缺少的字符处理和任何其他边缘情况
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python