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
