──────────────────────────────────────

18. Repair Desk Intake · Clean Text One Line at a Time

Use a generator to pass cleaned entries downstream one at a time.

Lesson files · lessons/iterators-and-toolkit/yield-clean-records

Before you start
- Use next() on an iterator and trace where a loop resumes.
- Use strip(), startswith() and upper() to check and clean text.

By the end
- Write a generator that yields each cleaned tag in input order.
- Show that blank and comment lines produce no tags.
- Trace where the generator pauses and resumes between two values.

Where you can use it
A label printer can start on the first cleaned repair tag while the rest of the intake sheet is still being read.

Calling a function with yield returns a generator. The body starts when next() or a for loop first asks for a value. Each yield hands over one value and pauses the function. When the next value is requested, the function resumes with its variables intact.

The example strips spaces, skips blank lines and yields one upper-case tag at a time. The same function can take a list, an open text file or sys.stdin. Looping over sys.stdin reads one line of Program input at a time, so you can clean tags without building a second list.

Predict
When does clean_tags start reading its input lines?
- As soon as the program assigns tags.
- When the first next(tags) requests a value.

Worked example (example.py)

def clean_tags(lines):
    for raw in lines:
        tag = raw.strip()
        if tag:
            yield tag.upper()


tags = clean_tags(["  r18 ", "   ", "r07"])
print(next(tags))
print(next(tags))
print(next(tags, "Done"))


Example result
R18
R07
Done

Complete clean_tags(lines) for repair tags entered one per line. Strip spaces from each line, then skip blank lines and lines that start with #. Use yield to pass each remaining tag in upper case. Keep the loop that prints “Tag: ” followed by each result.

Starter program (starter.py)

import sys


def clean_tags(lines):
    for raw in lines:
        tag = raw.strip()
        if tag:
            yield tag


for tag in clean_tags(sys.stdin):
    print(f"Tag: {tag}")


Starter input

 r14 
 # tea break
R08

Hint
Test tag.startswith("#") after strip(). Your generator can skip the line with continue or yield only inside an if block.

Case 1. Try the sample
Input

 r14 
 # tea break
R08
Expected output
Tag: R14
Tag: R08

Case 2. Only comments and blank lines
Input
# paused
 
  # sign-off
Expected output
(No output.)

Case 3. Repeated tags
Input
r2
r2
Expected output
Tag: R2
Tag: R2

Stretch
Use enumerate(lines, start=1) to keep original line numbers. Yield a tuple of the line number and cleaned tag, then show both in the output.

Reflect
What happens in the example if you replace yield tag.upper() with return tag.upper()?

Check your prediction
When the first next(tags) requests a value. The assignment creates the generator. The first next() runs it until the first yield.
