Skip to main content

How to Decrypt Acrostic Poems in Python Using Regex

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.
note

We use the re library instead of standard string methods because re.split() allows us to split by multiple delimiters (both comma and dot) simultaneously using a single pattern [,.].

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]:
# ✅ Correct: Check for None or empty string immediately
if not poem:
return None
# ... logic continues

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).

# List comprehension to clean and extract first word
# 1. line.strip() removes spaces around the segment
# 2. .split(" ")[0] gets the first word
words = [line.strip().split(" ")[0] for line in lines if line.strip()]

# Note: The 'if line.strip()' check prevents empty strings from processing,
# though the logic below handles it naturally too.

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.
"""
# ✅ 1. Handle empty input
if not poem:
return None

# ✅ 2. Split the poem into lines using regex
# Pattern [,.] matches either a comma or a period
lines = re.split(r"[,.]", poem)

# ✅ 3. Extract the first word from each line
# We iterate over 'lines'. For every line:
# - strip() removes leading/trailing whitespace (important after commas)
# - split(" ")[0] takes the first word
words = [line.strip().split(" ")[0] for line in lines]

# ✅ 4. Concatenate the result
decryption_text = "".join(words)

return decryption_text

if __name__ == "__main__":
# Test Data
string = "Rain is falling all around, It falls on field and tree. It rains on the umbrella here, And on the ships at sea."

# Execution
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
tip

In the list comprehension words = [...], if the regex split results in an empty string (e.g., after the final period), line.strip() becomes empty. Splitting an empty string "" results in [''], and the first element is "". Joining this empty string into the result has no effect, which is the desired behavior.

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.