【问题标题】:How to encrypt a code on python, where a string is encrypted into a secret code?如何在python上加密代码,其中字符串被加密为密码?
【发布时间】:2015-08-15 08:25:30
【问题描述】:

我应该使用循环加密任何字符串,其中一些字母会更改为特殊符号,例如 a=@ e=() h=# l=1 等等。老实说,我不知道该怎么做。无法使用替换功能。到目前为止,我有这个,但我知道这是错误的。

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

【问题讨论】:

  • 您可以使用哪种数据结构来存储两个字符串之间的关系?
  • 只是字符串替换。要解密,您将拥有 '@' = 'a'
  • @Daniela - 我注意到您试图通过编辑答案来回复。表明答案是好的或有帮助的正确方法是使用左侧栏中的向上箭头对其进行投票,如果它解决了您的问题,请使用勾号接受,如中所述help。谢谢。

标签: python string encryption


【解决方案1】:

你不能使用替换?完美,因为您应该改用translate

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

但是我觉得您的讲师希望您学习如何遍历明文,查找正确的值,并将其添加到累加器字符串中。在伪代码中:

function encrypt(cleartext):
    encrypted = ""
    for each character in cleartext:
        if character == 'h':
            encrypted += "#"
        elif character == "a":
            encrypted += "@"
        ...
    return encrypted

我会这样做:

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

但如果你在不理解的情况下上交,我相信你的老师会辜负你的!

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

    • Giant if..elif 这样的块很快就会变得笨拙(而且你错过了结束 ')。
    • 感谢@TigerhawkT3 指出缺少的报价。是的,elif 块确实不是最好的解决方案,但是如果您查看问题中的代码 sn-p,我们可以同意任何其他更短更好的实现,虽然可以完成工作,但可能会令人困惑.我只是将提供的代码转换成可以工作的东西。
    • @Daniela:您可能想添加评论,而不是编辑答案:)
    【解决方案3】:

    代码:

    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
    

    测试:

    >>> encryption('shell')
    '$#()11'
    >>> encryption('shellac')
    '$#()11@?'
    

    【讨论】:

      最近更新 更多