Home > OS >  Encrypting a string by replacing letters between two strings
Encrypting a string by replacing letters between two strings

Time:02-14

I want to create a function which will receive two strings as parameters. One will be the the phrase to be encrypted and the other one will be some sort of index used to encrypt. The process is based on a alphabet 'abcdefghijklmnopqrstuvwxyz .'. Each letter in the first string will have its corresponding letter found in the second string. Its position number will determine which letter of 'abcdefghijklmnopqrstuvwxyz .' will be used at the result. For example:

>>> func('hello world', '. zyxwvutsrqponmlkjihgfedcba')
    'uxqqnbfnkqy'

While searching, I found out some methods to do it, but they used external libraries. Is there a way to do it without them?

Thanks in advance for any help.

CodePudding user response:

You certainly don't need any external libraries.

Just use the index method to find the characters position within the alphabet, then use that index to get the corresponding character in the cypher key.

def func(string, key):
    letters = 'abcdefghijklmnopqrstuvwxyz .'
    output = ''
    for char in string:
        output  = key[letters.index(char)]
    return output
    

CodePudding user response:

This function I wrote may help you.

def encrypt(message, key):
    alphabet = 'abcdefghijklmnopqrstuvwxyz .'
    encrypted_message = ""
    for character in message:
        index = key.find(character)
        encrypted_message  = alphabet[index]
    return encrypted_message

The most useful method to you is the find(character) method for strings. It is used to return the index of the first matching character in a string.

https://www.programiz.com/python-programming/methods/string/find

CodePudding user response:

Python's builtin translate() function does exactly what you want out of the box and it's orders of magnitude faster on larger strings than looping:

def f(s, key):
    alphabet = 'abcdefghijklmnopqrstuvwxyz .'
    trans = str.maketrans(alphabet, key)
    return s.translate(trans)
    
f('hello world', '. zyxwvutsrqponmlkjihgfedcba')
# 'uxqqnbfnkqy'

You just need to make sure the alphabet and key code are the same length.

  • Related