Meaning
The replace method returns a new string where all occurrences of a specified substring are substituted with another substring. It leaves the original string unchanged because strings are immutable in Python. Use it when you need to transform text without altering the source.
Primary Function
String manipulation
Communicative Purpose
Create a modified copy of a string with specific substrings substituted.
Pattern
string.replace(old, new)
Core Structure
...replace(..., ...)
Função primária
String manipulation
Propósito comunicativo
Create a modified copy of a string with specific substrings substituted.
Situações de gatilho
Web development: updating URLs to a new domain; File management: changing file extensions from .txt to .md; Data cleaning: sanitizing user input by swapping prohibited tokens
Contextos
General‑purpose Python scripts, data‑cleaning pipelines, web back‑ends, command‑line utilities.
Padrão
string.replace(old, new)
Estrutura central
...replace(..., ...)
Slots de substituição
string: str; old: str; new: str
Colocados típicos
- str.upper()
- str.lower()
- str.strip()
- re.sub()
- f-strings
- str.join()
Substituições comuns
- Using re.sub for regex‑based replacement
- using str.translate for character‑wise mapping
- chaining multiple replace calls.
Erros comuns
Assuming replace mutates the original string; forgetting to assign the returned value; using replace when a regex pattern is needed.
Similar / contraste
re.sub performs pattern‑based (regex) replacement, while str.replace works on literal substrings; str.translate replaces characters via a translation table.
Interferências
Coming from languages with mutable strings (e.g., JavaScript), developers may expect an in‑place change.
Família do chunk
- String methods
- text processing
- immutability patterns
Nuance
replace replaces all occurrences unless a third count argument is provided; it is case‑sensitive and works on Unicode code points.
Efeito pragmático
Produces a new string without side effects, making code safer and easier to reason about.
Dica de memória
Find‑and‑replace: old → new.
Nota
Because strings are immutable in Python, replace always returns a new string; assigning the result is required to effect change.
Upgrade path
Use re.sub(pattern, repl, string) for regular‑expression based replacements or str.translate(table) for per‑character mapping.
Log in to save chunks.