Concepts / String Methods and Splitting

String Methods and Splitting

Splitting a line turns the input string into a list of words.

  • Programming

Why Lines Need Filtering

When a program parses a file line by line, it may care about only one kind of line. For example, the program might process lines that begin with the word From and ignore every other line. The difficulty is that lines do not always have the same structure. A line may be empty, or it may contain fewer words than the program expects. Reliable parsing therefore requires two decisions: which lines should be processed, and whether a line contains enough data to inspect safely.

Key point

The three techniques in this lesson work together: split a line into words, use guardian code before accessing a word by index, and use continue to skip lines that should not be processed.

Skipping with Continue

The continue statement ends the current loop iteration immediately and jumps back to the next iteration of the loop. Any code later in the current iteration is skipped. This makes it useful for rejecting lines early: when a line does not meet the criterion, continue prevents the rest of the processing logic from running for that line.

Input linecurrent lineMeets criterionfor example, starts withFromcontinueskip remaining codeNext iterationread the next lineProcess linecriterion is satisfiedinspectnojumpyes
When a line does not meet the criterion, how does control flow jump to the next loop iteration?

A common filtering test is to split the line into words and inspect the first word. If the first word is not From, the parser uses continue. The important control-flow detail is that the decision happens before the main processing logic, so rejected lines never reach that logic.

Splitting Lines into Words

Splitting a line turns the input string into a list of words. The delimiter separates the parts, and each resulting part occupies an element in the list. This gives the parser a way to inspect the first word directly and decide whether the line begins with the required text.

Input linewords separated bydelimitersSplitseparate the lineFirst wordlist element at index 0Other wordslater list elementssplit at delimitersproducesproduces
How does one input string become multiple list elements when a delimiter is encountered?
Worked example

Classifying a Line

A parser splits a line into words and wants to know whether the first word is From.

  1. 1
    Separate the line

    The line is split into a list of word elements.

  2. 2
    Check the first element

    The parser examines the first word to determine whether it is From.

  3. 3
    Choose a path

    If the first word is not From, the parser skips the rest of the current iteration with continue. If it is From, the line can move to the processing logic.

Result

Splitting supplies the list structure needed for the filtering decision, but the first element must be checked safely before it is accessed.

Protecting Index Access

Accessing the first word is unsafe when the split result may be empty. An empty line produces no first word, so trying to inspect the element at index 0 raises an IndexError before the program can reach its continue statement. Guardian code prevents this failure by checking the list before accessing an index.

Word listresult of splittingList is emptycheck before index 0continuedo not access index 0First wordsafe index accesscheckyesno
How does checking the list before index access prevent an out-of-range access?
Best practice

Place every guardian check before the code it protects. Here, the check that the word list is not empty must happen before the parser examines the first word. This ordering guarantees that the protected access is reached only when a first element exists.

Combining Skip Conditions

A parser may need to skip a line for more than one reason. It should skip an empty word list, or skip a nonempty list whose first word is not From. The or operator combines these alternatives in one compound condition. The complete condition is true when at least one of its component conditions is true, so continue runs whenever either reason requires the line to be rejected.

Empty listfirst alternativecontinueskip current lineFirst word is notFromsecond alternativeProcess lineneither alternative is truetruetruefalse, then check other conditionfalse
How do multiple alternative conditions combine, and when does the overall expression become true?
ConditionMeaningResult
The list is emptyThere is no first word to inspectSkip the line
The first word is not FromThe line does not meet the processing criterionSkip the line
Neither condition is trueThe list has a first word and it is FromContinue processing

The or condition handles either reason for rejecting a line.

Combining the alternatives reduces duplicated continue statements and keeps the filtering rule in one place. The guardian part still has priority conceptually: the expression must not attempt to inspect the first word when the list is empty. The safety check belongs before the access it protects, even when the final design combines skip conditions.

Mistakes in File Parsing

  • Common mistake

    Accessing the first word before checking whether the list contains an element.

    What it looks like

    An empty line is split, and the parser immediately examines the element at index 0.

    Why it fails

    An empty list has no first element, so the access raises an IndexError before the skip logic can run.

    Do this instead

    Check the list length or otherwise verify that it is not empty before accessing index 0.

  • Common mistake

    Putting the guardian check after the protected access.

    What it looks like

    The parser examines the first word and only afterward checks whether the list was empty.

    Why it fails

    The program has already attempted the unsafe operation by the time the check runs.

    Do this instead

    Place the guardian before every access it protects.

  • Common mistake

    Using separate repeated branches when the line should be skipped for either of two reasons.

    What it looks like

    One branch skips empty lists and another separate branch skips lines whose first word is not From.

    Why it fails

    The logic works but is more verbose and duplicates the same skip action.

    Do this instead

    Combine the alternative skip conditions with the or operator in one if statement.

  • Common mistake

    Assuming every input line has the same structure.

    What it looks like

    The parser expects every line to contain three words.

    Why it fails

    Real input may include empty lines or lines with fewer words than expected, which can make an index unavailable.

    Do this instead

    Test parsing logic with empty lines and lines containing fewer words than expected.

Practice the Control Flow

MEDIUM

Suppose a parser should process only lines whose first word is From. Describe the order of checks it should perform when a line has been split into a list of words. Include what should happen for an empty list, for a nonempty list whose first word is not From, and for a nonempty list whose first word is From.

Hints
  • Identify the condition that must be checked before any first-word access.
  • Use continue for both kinds of rejected lines.
  • The final case is the one in which neither skip condition is true.

What do you think happens?

A line is empty after splitting. Which action should occur first: inspect the first word, or skip the line because the list has no elements?

  • Inspect the first word

  • Skip the line because the list is empty

Reveal answer
Answer:

Skip the line because the list is empty

The guardian check must occur before index access. Otherwise, trying to inspect the first word can raise an IndexError before continue is reached.

Reliable Parsing Pattern

  1. 1
    Split each input line into words when the parser needs to inspect individual parts.
  2. 2
    Check that the resulting list contains enough elements before accessing an index.
  3. 3
    Use continue to skip an empty or otherwise unwanted line immediately.
  4. 4
    Combine alternative skip conditions with or when either condition should lead to the same continue action.
  5. 5
    Test the parsing logic with empty lines and lines containing fewer words than expected.

The central idea is ordering: guard first, decide second, and process only after the line is known to be safe and relevant. Splitting exposes the parts of a line, guardian code prevents invalid access to those parts, continue removes unwanted lines from the remaining work, and or expresses multiple acceptable reasons to skip in one condition.

Key Takeaways

  • Use continue to jump immediately to the next loop iteration when a line does not meet the processing criterion.
  • Split a line into words when the parser needs to inspect individual words.
  • Check a list before accessing an index so empty or short input does not cause an IndexError.
  • Use the or operator when either of multiple conditions should cause the same line to be skipped.
  • Place guardian checks before the access they protect and test with empty and short lines.

Related concepts

More concepts starting with S