Showing posts with label Yield. Show all posts
Showing posts with label Yield. Show all posts

Friday, September 13, 2024

Extracting Underscored Words Using Python Generators

Extract Words Enclosed in Underscores using Python Generators

Extract Words Enclosed in Underscores using Python

๐Ÿ“š Table of Contents

๐Ÿงฉ Problem Statement

You are given a list of strings. Some words are wrapped in underscores like _example_.

Your task is to extract only those words that start and end with underscores.

⚙️ Step-by-Step Approach

1. Combine Input Strings

We merge all strings into one large string using join() to simplify processing.

2. Split into Words

We split the combined string using spaces to get individual words.

3. Filter Words

Check if a word starts and ends with _.

4. Use Generator (yield)

Instead of returning all results at once, we use yield to produce results lazily.

๐Ÿ’ป Code Example

def get_underscored(strings):
    combined = " ".join(strings)
    for word in combined.split():
        if word.startswith("_") and word.endswith("_"):
            yield word

# Input data
strings = [
    "This is a _test_ string",
    "Another _example_ here",
    "No underscores here",
    "Check _this_ out"
]

# Collect results
result = list(get_underscored(strings))
print(result)

๐Ÿ–ฅ️ CLI Output

$ python script.py
['_test_', '_example_', '_this_']

๐Ÿง  Interactive Learning

⚡ Try It Yourself (Interactive)

Enter multiple sentences (one per line). Words wrapped with underscores will be extracted instantly.


Output:





What does yield do?

yield pauses function execution and returns a value one at a time.

This makes it memory efficient.

Why use generators?
  • Efficient for large datasets
  • Lazy evaluation
  • Better performance

๐Ÿ’ก Key Takeaways

  • Generators use yield instead of return
  • They produce values one at a time
  • Useful for memory-efficient processing
  • Great for streaming or large inputs

Featured Post

How HMT Watches Lost the Time: A Deep Dive into Disruptive Innovation Blindness in Indian Manufacturing

The Rise and Fall of HMT Watches: A Story of Brand Dominance and Disruptive Innovation Blindness The Rise and Fal...

Popular Posts