replace()
A string method that returns a copy of a string with every occurrence, or the first few, of one piece of text replaced by another.
In more detail
s.replace("a", "o") changes all; s.replace("a", "o", 1) only the first. The original string is unchanged, because strings are immutable, so assign the result: s = s.replace(...).
Example
"banana".replace("a", "o", 2) # "bonona"Related terms
- string method — A method that belongs to strings, such as upper, lower, count, find, replace, split, strip, startswith or join.
- immutable — Something that cannot be changed after it is created; to change it you make a new one.
Taught in
- Chapter Three In One Sitting — Hands-on Python: Complete Video Course & Book