Python strip() and replace(): Clean Simple Text
Core idea
text.strip() returns text without leading and trailing whitespace. text.replace(old, new) returns a string with matching occurrences of old replaced by new. These operations do not change the original string. Use the returned value or assign it back to a name.
raw = " tea_bag "clean = raw.strip().replace("_", "-")print(clean)print("[" + raw + "]")The first method returns trimmed text, then the second method replaces the underscore. Brackets reveal the preserved spaces in the original.
Strip removes a set of edge characters
print("ab-data-ba".strip("ab-"))print(" a b ".strip())With an argument, strip removes any of those individual characters from both ends until it meets another character. It does not remove an exact prefix or suffix, or whitespace in the middle. The first result is dat, not data: the final a is also in the removal set.
Limit replacements
text = "a-a-a"print(text.replace("a", "b"))print(text.replace("a", "b", 1))The optional third argument limits the number of replacements. Without it, all non-overlapping matches are replaced.
Common mistake
Writing text.strip() alone does not update text. Also, strip("ab") does not mean remove the exact substring ab. Use replace for substring replacement, and retain the result.
Practice
Clean " red__bag " into "red--bag" without removing the spaces inside other labels.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Strip and replace
Check your understanding of strip and replace.
What is printed?
print("[" + " a b ".strip() + "]")What is printed?
print("a-a-a".replace("a", "x", 1))What is printed?
word = "cat"word.replace("c", "b")print(word)What does text.strip("ab") remove?