COGNITION FOUNDRYLEARN. BUILD. UNDERSTAND.
PY-020 / Targeted string transformations◷ 18 min read + practice

Finding, splitting and replacing text

Cleaning a string is rarely about deleting everything that looks inconvenient. It is about identifying a precise pattern and changing only what the user intended.

By the end, you can: Use membership tests, find(), split(), join() and replace() for deliberate text operations.
Before this lesson: PY-019

Find a known piece of text

The membership expression ".txt" in filename produces a Boolean. The method find() returns the starting position of a match, or -1 when no match exists.

For a file extension, endswith() is often clearer than searching for a fragment anywhere in the filename. notes.txt.backup contains .txt but does not end with it.

Split records with a known delimiter

The method split(",") separates a string into pieces. Use join() to rebuild a string with a chosen separator. For genuine CSV data with quoting and escaped delimiters, use Python’s csv module rather than an improvised split.

That distinction is fundamental: a demonstration works for deliberately simple input, while a production tool must handle the format’s full rules.

Replace exact sequences

replace(old, new) creates a new string and does not modify the original string in place. You can limit the number of replacements with the optional third argument.

Replacing every backslash in a path with two backslashes is appropriate when creating an escaped Python source representation. It is not the same as changing the path stored on disk.

Design the transformation as a function

A predictable function accepts a string and returns the transformed version. Test inputs where the target sequence exists, does not exist and appears more than once.

Avoid broad replacements when you could express a narrower operation. This is especially important for filenames and paths, where each character may have meaning.

Try it yourself.

Choose a starting example or write something completely different. You control the code; the Run button executes what is in the editor, not a hidden preset.

CF Python PlaygroundBrowser-based Python
Ready to load Python
Membership and endings

Compare contains-anywhere with exact filename ending.

Syntax colours highlight Python code. Tab inserts four spaces; press Escape then Tab to leave the editor. Ctrl+Enter runs the current code.
OUTPUT / ERRORS
Press Run Python to execute the editable code.
NOW MAKE IT YOURS

Change the filename so both checks return True.

Need a hint?

Make the name finish with .txt instead of .backup.

On first Run, a pinned Python runtime downloads from jsDelivr. Code executes locally in your browser's Web Worker, not on our server. It cannot inspect your normal PC files or Windows hardware. Avoid entering secrets. Heavy/infinite loops are stopped by a time limit.

Check your understanding.

Try answering each question before opening its reference answer. Explain the idea aloud or change an example to test it for yourself.

  1. What is the difference between checking .txt with in and with endswith()?

    View answer

    ".txt" in name checks whether those four characters appear anywhere in the filename, even in the middle. name.endswith(".txt") checks only the end, which is usually what you want for a simple suffix test. For robust path-extension handling, later use pathlib rather than manually assuming every filename has one suffix.

  2. Why should a real CSV reader use the csv module instead of a plain split(",")?

    View answer

    A CSV field can contain a comma inside quoted text, as well as escaped quotes and line breaks. split(",") does not understand those rules and can split a single field into several pieces. Python’s csv module implements the format rules and is the correct starting point for a real data tool.

Where this leads.

Next we apply precise string operations to Windows paths and Python string literals.