Python Forum
Simple encoding code - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Simple encoding code (/thread-37488.html)



Simple encoding code - ebolisa - Jun-17-2022

Hi,

This simple encoding code converts text to ASCII and adds a one digit number to it. It seems to work ok, but while testing it, I noticed that if a 'v' is used, it's converted to ' ' when a 9 is added to it. (probably bc it's hitting ascii 127 - delete). Is there a way to fix it?

TIA

encoded_txt = ''
key = 0


def encode_text():
    global encoded_txt, key
    arry = []

    txt = input("Enter an alphanumeric text: ")
    while True:
        try:
            key = int(input('Enter a single digit number: '))
            if key > 9:
                n = 1 / 0  # force to fail
            break
        except:
            print("That's not a valid option!")

    # fill array with entered text
    for _ in range(len(txt)):
        arry.append(txt[_])

    # add pass to characters
    for char in range(len(arry)):
        x = ord(arry[char]) + key
        # convert ascii to char
        encoded_txt += chr(x)

    print("Encoded text:", encoded_txt)


encode_text()
Output:
Enter an alphanumeric text: vince Enter a single digit number: 9 New text: rwln Decoded text: vince



RE: Simple encoding code - deanhystad - Jun-18-2022

Limit your alphabet to only visible characters. This example limits the alphabet to upper and lowercase letters,
import string
 
letters = string.ascii_uppercase + string.ascii_lowercase

def encode_text(text, shift):
    code = dict(zip(letters, letters[shift:] + letters[:shift]))
    return "".join([code[letter] for letter in text])

encoded = encode_text("vince", 9)
print(encoded, encode_text(encoded, -9))



RE: Simple encoding code - ebolisa - Jun-18-2022

(Jun-18-2022, 12:45 AM)deanhystad Wrote: Limit your alphabet to only visible characters. This example limits the alphabet to upper and lowercase letters,

Thank you. It works even with a little modification:

letters = string.ascii_letters + string.digits + string.punctuation



RE: Simple encoding code - deanhystad - Jun-18-2022

Maybe use ascii_printable. If you want punctuation you probably also want whitespace.