liveBook · Manning

Replace method

As explained in Get Programming: Learn to code with Python

replace is a Python string method that returns a string with occurrences of one substring substituted by another substring.

The replace() method substitutes every occurrence of one substring with another. Put the substring to find first and the replacement substring second, separated by a comma. section 8.1

Replace spaces with underscores

"variables have no spaces".replace(" ", "_") evaluates to "variables_have_no_spaces". The first argument is the text to find; the second is the text inserted in its place. section 8.1

Try these quick checks with a = "Raining in the spring time.":

  • a.replace("R", "r") changes the initial capital letter. section 8.1
  • a.replace("ing", "") removes each matching occurrence. section 8.1
  • b = a.replace("time", "tiempo") stores the changed string in b. section 8.1

How Get Programming: Learn to code with Python covers it

How deep it goes
Demonstrates the two-argument form with worked replacements and quick checks, without descending into implementation details.
Examples
Uses spaces, letters, removed substrings, punctuation, and translated words as replacement examples.
What you can do after
Apply it via Python to replace, remove, or revise matching substrings in a string.
How it connects
Connects substring replacement with string operations and count().

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 Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.