如何在python上加密代码,其中字符串被加密为秘密代码?

2024-04-20 08:03:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我应该用一个循环来加密任何字符串,在这个循环中一些字母会变成特殊的符号,比如a=@e=()h=#l=1等等。我真的不知道怎么做。无法使用函数replace。到目前为止我有这个,但我知道这是错的。在

 encryption(code):
    encrypted = ''
    for c in code:
        if c != '':
            a='@'
            e='()'
            h='#'
            l='1'
            r='+'
            s='$'
            v='^'
            x='*'
    return The encrypted code is:

Tags: the函数字符串inforreturnifis
3条回答

你不能用替换?很好,因为您应该使用translate。在

def encrypt(cleartext):
    mapping = {'a':'@',
               'e':'()',
               'h':'#', ...}
    transdict = str.maketrans(mapping)
    enctext = cleartext.translate(transdict)
    return enctext

不过,我觉得你的讲师希望你学习如何迭代明文,查找正确的值,并将其添加到累加器字符串中。伪代码:

^{pr2}$

我会做一些类似的事情:

def encrypt(cleartext):
    mapping = {'a':'@',
               'e':'()', ... }
    return ''.join(mapping.get(ch, ch) for ch in cleartext)

但是如果你不理解就把它交上来,我相信你的老师会让你失望的!在

代码:

def encryption(text):
    if not text:
        return 'No text present.'
    encrypted = ''
    encryption_key = {'a':'@', 'e':'()', 'h':'#', 'l':'1',
                      'r':'+', 's':'$', 'v':'^', 'x':'*'}
    for c in text:
        encrypted += encryption_key.get(c, '?')
    return encrypted

测试:

^{pr2}$
def encryption(code):
    encrypted = ''
    for c in code:
        if c == 'a':
            encrypted = encrypted + '@'
        elif c == 'e':
            encrypted = encrypted + '()'
        elif c == 'h':
            encrypted = encrypted + '#'
        elif c == 'l':
            encrypted = encrypted + '1'
        elif c == 'r':
            encrypted = encrypted + '+'
        elif c == 's'
            encrypted = encrypted + '$'
        elif c == 'v'
            encrypted = encrypted + '^'
        elif c == 'x'
            encrypted = encrypted + '*'
        #here you can add other characters that need to be encrypted in elif blocks.
        else:
            encrypted = encrypted + c
    return encrypted

相关问题 更多 >