[Python] How do I encrypt by index? ... or encrypt by pattern?

Discussão em 'Python' iniciado por Stack, Setembro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am a beginner, considering doing a course if I can get my head around the basics. I am playing around with encryption but cannot seem to get some basic concepts.

    I have managed to get a caesar cipher (below), but now I want to:

    1. shift characters by index e.g odds move +3 evens move -2
    2. shift by binary pattern e.g 01100101 where 0s move -1 1s move +1

    (I have kept uppercase, lowercase, and numbers the same. and I have ignored spaces and symbols)

    Everywhere I am reading about encryption have many ways of doing encryption code, but nothing that keeps it seemingly simple for beginners like me (or I am just reading things wrong)

    def encrypt_text(message: str, shift: int) -> str:
    encrypted_message = ""
    for char in message:
    if 'a' <= char <= 'z': # encrypt lowercase letters
    shift_char = ord(char) + shift
    if shift_char > ord('z'):
    shift_char -= 26 # wrap around within the alphabet
    encrypted_message += chr(shift_char)
    elif 'A' <= char <= 'Z': # encrypt uppercase letters
    shift_char = ord(char) + shift
    if shift_char > ord('Z'):
    shift_char -= 26 # wrap around within the alphabet
    encrypted_message += chr(shift_char)
    elif '0' <= char <= '9': # encrypt numbers
    shift_char = ord(char) + shift
    if shift_char > ord('9'):
    shift_char -= 10 # wrap around within 0-9
    encrypted_message += chr(shift_char)
    else: # ignore non-alphanumeric characters
    encrypted_message += char
    return encrypted_message

    message = input("Message to encrypt: ") # ask user for message
    shift_value = int(input("Shift: ")) # "shift every char forward by +3 in the alphabet"
    encrypt_result = encrypt_text(message, shift_value)
    print(f"Encryption message: {encrypt_result}")


    This code works for me. How can I adapt this to my questions?

    Continue reading...

Compartilhe esta Página