liveBook · Manning

Replace method

As explained in The Quick Python Book, Fourth Edition

replace is a Python string method that returns a copy with occurrences of a specified substring replaced by another string, optionally limiting the number of replacements.

Python’s `replace` string method substitutes occurrences of one substring with another. Call `text.replace(old, new)` to get a new string; the original remains unchanged because strings are immutable. An optional third argument limits the number of replacements. section 6.4.5

x = "Mississippi"
x.replace("ss", "+++")
 
'Mi+++i+++ippi'

Both occurrences of `ss` become `+++` in the returned string. section 6.4.5

Normalize before counting words

`moby = "There, now.".lower()`; then `moby = moby.replace(".", "").replace(",", "")`. Calling `moby.split()` now gives `['there', 'now']`. Reassign the result of each call: `replace` does not modify `moby` in place. section 21.2.2 section 6.4.5

Repeated calls are convenient for a few substitutions. For many punctuation characters, `translate` can handle them in one operation; looping over punctuation and calling `replace` for every line repeatedly creates new strings. For more powerful substring replacement, use the `re` module. section 21.2.2 section 6.10.2 section 6.4.5

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines the two required arguments and immutable return value, but defers details of the optional third argument to documentation.
Examples
Shows `ss` replaced in `Mississippi` and periods and commas removed from lowercased file text.
What it assumes
Assumes basic Python string and method-call familiarity while explaining what replace returns.
What you can do after
Practice/perform substring substitution and basic text normalization while choosing translate for numerous character substitutions.
How it connects
Connects string immutability and text normalization with lower(), split(), translate(), and regular expressions.

Also explained in

Compare how 5 books explain replace method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.