如何为字符串中的每个字母分配一个值,然后将这些值添加到另一个字符串中?”

时间:2018-09-01 08:48:37

标签: python string

def code_maker():

    values = {"a":0, "b":1, "c":2, "d":3, "e":4, "f":5, "g":6, "h":7, "i":8, "j":9, "k":10, "l":11, "m":12, "n":13, "o":14, "p":15, "q":16, "r":17, "s":18, "t":19, "u":20, "v":21, "w":22, "x":23, "y":24, "z":25}

    key = input("Please enter a four letter key ").lower()
    code = input("Please enter a string ").lower()

    added_code = (key[0] + code[0]) + (key[1] + code[1]) + (key[2] + code[2]) + (key[3] + code[3]) 

我正在尝试做一个凯撒密码类型的事情,我将一个字符串中的每个字母分配给相应的数字,然后将其值添加到另一个字符串中的另一个字母,但是我不知道如何找到与之关联的每个字母值。

2 个答案:

答案 0 :(得分:1)

您不想使用已经编写的代码吗?在here中,您可以找到以下内容:

 # Caesar Cipher



MAX_KEY_SIZE = 26



def getMode():
    while True:
         print('Do you wish to encrypt or decrypt a message?')

         mode = input().lower()

         if mode in 'encrypt e decrypt d'.split():

             return mode

         else:

             print('Enter either "encrypt" or "e" or "decrypt" or "d".')



def getMessage():

    print('Enter your message:')

    return input()



def getKey():

    key = 0

    while True:

        print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))

        key = int(input())

        if (key >= 1 and key <= MAX_KEY_SIZE):

            return key



def getTranslatedMessage(mode, message, key):

    if mode[0] == 'd':

        key = -key

    translated = ''



    for symbol in message:

        if symbol.isalpha():

            num = ord(symbol)

            num += key



            if symbol.isupper():

                if num > ord('Z'):

                    num -= 26

                elif num < ord('A'):

                    num += 26

            elif symbol.islower():

                if num > ord('z'):

                    num -= 26

                elif num < ord('a'):

                    num += 26



            translated += chr(num)

        else:

            translated += symbol

    return translated



mode = getMode()

message = getMessage()

key = getKey()



print('Your translated text is:')

print(getTranslatedMessage(mode, message, key))

它将询问您是否要解密或加密消息。说如果要加密。然后,它要求提供密钥号。比消息更重要,它输出消息的加密版本。

答案 1 :(得分:0)

尝试zip()。

def code_maker():
    values = {"a":0, "b":1, "c":2, "d":3, "e":4, "f":5, "g":6, "h":7, "i":8, "j":9, "k":10, "l":11, "m":12, "n":13, "o":14, "p":15, "q":16, "r":17, "s":18, "t":19, "u":20, "v":21, "w":22, "x":23, "y":24, "z":25}

    key = input("Please enter a four letter key ").lower()
    code = input("Please enter a string ").lower()
    print(list(zip(key,code)))

输出:

Please enter a four letter key abcd
Please enter a string wxyz
[('a', 'w'), ('b', 'x'), ('c', 'y'), ('d', 'z')]

如果需要其他格式的输出,请告诉我。