transformation
str.replace
Returns a new string with all occurrences of substring old replaced by new. If count is given, only the first count occurrences are replaced.
str.replace(old, new[, count]) Parameters
| Parameter | Purpose |
|---|---|
| old | substring to search for |
| new | substring to substitute in |
| count | maximum number of replacements (default: all) |
Examples
>>> 'hello world'.replace('world', 'there')
'hello there' single replacement
>>> 'a.b.c.d'.replace('.', '-')
'a-b-c-d' all occurrences replaced by default
>>> 'a.b.c.d'.replace('.', '-', 2)
'a-b-c.d' count caps the number of replacements
>>> 'hello'.replace('l', '')
'heo' empty `new` deletes the matches
Gotcha
Strings are immutable — replace returns a new string; the original is unchanged. For regex patterns use re.sub() instead.
Related methods
str.strip
Returns a copy of the string with leading and trailing whitespace removed. If chars is given, removes any leading/trailing characters that appear in the chars set (not a prefix/suffix — it is a character set).
str.count
Returns the number of non-overlapping occurrences of substring sub in [start:end]. Overlapping matches are not counted.
str.format
Substitutes replacement fields delimited by { } in the string with values from args and kwargs, using the Format Specification Mini-Language. In modern Python, f-strings are usually preferred for literals; str.format() remains ideal for templates loaded at runtime.
str.upper
Returns a copy of the string with all cased characters converted to uppercase. Non-cased characters (digits, punctuation, whitespace) are unchanged.
str.lower
Returns a copy of the string with all cased characters converted to lowercase. Uses Unicode simple lowercase mappings.