Skip to content

How to Decrypt Acrostic Poems in Python Using Regex

Learn how to extract the first word from each sentence in an acrostic poem using Python regex to reveal the hidden message by splitting on commas and periods.

An acrostic poem is a form of writing where the first letter or word of each line spells out a hidden message. In this guide, we will implement a Python function to decrypt such poems. The goal is to extract the first word of every sentence (delimited by commas or periods) and concatenate them to reveal the hidden string.

We will use Python's built-in re (Regular Expression) library to handle the text splitting efficiently.

Understanding the Algorithm

To decrypt the message based on the specific rules of this challenge, we need to perform the following operations:

  1. Validation: Ensure the input is valid. If the poem is empty or None, the function should return None.
  2. Splitting: The text serves as a stream of sentences separated by punctuation. We need to split the string wherever a comma (,) or a period (.) occurs.
  3. Extraction: From every resulting segment (line), we strip whitespace and extract the first word.
  4. Concatenation: Join these words together to form the final result.

Step-by-Step Implementation

Handling Edge Cases

First, we must ensure the function handles empty inputs gracefully using a guard clause.

from typing import Optional

def acrostic_poetry_decryption(poem: str) -> Optional[str]:
    if not poem:
        return None

Splitting with Regex

We use re.split(r"[,.]", poem) to break the text into chunks.

import re

text = "Rain is falling, It falls."
lines = re.split(r"[,.]", text)
print(f"Split lines: {lines}")

Output:

Split lines: ['Rain is falling', ' It falls', '']

Extracting and Joining

We iterate through the split lines, strip leading/trailing whitespace, and take the first token (word).

words = [line.strip().split(" ")[0] for line in lines if line.strip()] 

Complete Code Solution

Here is the complete, runnable script. It includes the acrostic_poetry_decryption function and a test block to verify the output.

import re
from typing import Optional

def acrostic_poetry_decryption(poem: str) -> Optional[str]:
    """
    Decipher the message in the acrostic poem by extracting the first words 
    of each line (split by ',' or '.') and linking them together.
    """
    if not poem:
        return None

    lines = re.split(r"[,.]", poem)

    words = [line.strip().split(" ")[0] for line in lines]

    decryption_text = "".join(words)

    return decryption_text

if __name__ == "__main__":
    string = "Rain is falling all around, It falls on field and tree. It rains on the umbrella here, And on the ships at sea."
    
    result = acrostic_poetry_decryption(string)
    
    print(f"Original Text: {string}")
    print(f"Decrypted:     {result}")

Output:

Original Text: Rain is falling all around, It falls on field and tree. It rains on the umbrella here, And on the ships at sea.
Decrypted:     RainItItAnd

Conclusion

By combining Python's re module with list comprehensions, you can efficiently parse and transform unstructured text.

  1. re.split(r"[,.]", text) breaks the text on multiple delimiters.
  2. str.strip() cleans up the noise around the data.
  3. str.split(" ")[0] isolates the target data (the first word).

This approach provides a robust way to uncover hidden messages in acrostic strings.

Navigation