Extract Words Enclosed in Underscores using Python
๐ Table of Contents
- Problem Statement
- Approach
- Code Example
- CLI Output
- Interactive Learning
- Key Takeaways
- Related Articles
๐งฉ 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
yieldinstead ofreturn - They produce values one at a time
- Useful for memory-efficient processing
- Great for streaming or large inputs
No comments:
Post a Comment