liveBook · Manning

String replacement

As explained in Get Programming: Learn to code with Python

String replacement is the operation of substituting selected or all occurrences of text within a string with other text.

String replacement substitutes selected text inside a string with other text. In Python, replace() takes the substring to find and the replacement substring, then replaces every matching occurrence. section 8.0 section 8.1

Replacing spaces and words

The expression "variables have no spaces".replace(" ", "_") produces "variables_have_no_spaces". Here, " " is the text to find, and "_" is its replacement. Similarly, a report can change every occurrence of "apple" to "pear". To save a result, assign the expression: b = a.replace("time", "tiempo"). section 8.1

Replacement can also remove text or change its capitalization:

  • a.replace("R", "r") changes the capital R to lowercase. section 8.1
  • a.replace("ing", "") removes every matching "ing" substring. section 8.1
  • a.replace("!", ".") changes exclamation marks to periods; if no match exists, the shown operation makes no replacement. section 8.1

A practical workflow is to split a large text into lines, replace common abbreviations such as "pls" with "please," and count words or abbreviations afterward. This makes informal text easier to analyze. section 8.0

Quick check: use string operations to turn "Eat Work Play Sleep repeat" into "working playing". section 8.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains replace() syntax with worked examples, but does not descend into implementation details.
Examples
Uses word substitution, space-to-underscore conversion, deletion, capitalization changes, punctuation changes, and abbreviation cleanup.
What it assumes
Assumes basic string objects and substrings, while teaching replacement arguments through simple examples.
What you can do after
Apply via Python's replace() method to substitute, remove, or revise all matching substrings.
How it connects
Connects string replacement with substrings, string objects, string searching, and counting occurrences.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.