PythonString methods
str. replace()
Returns a string with occurrences of a given fragment replaced.
- Returns
- A new string.
- Changes the original
- No
Example
#Python
price = "3,50 EUR"
print(float(price.replace(" EUR", "").replace(",", ".")))
text = "cat and cat and cat"
print(text.replace("cat", "dog", 2))
print(text.replace("Cat", "dog"))Resultsaved result, you can check it
3.5
dog and dog and cat
cat and cat and cat
Definition and usage
#The replace(old, new) method returns a copy of the string in which every occurrence of the old fragment has been replaced with new. The original does not change.
The third argument count limits the number of replacements: replace("a", "b", 1) replaces only the first occurrence. The replacement is case-sensitive.
For pattern-based replacements, for example all digits or repeated spaces, use the re.sub() function from the re module.
Syntax
#Syntax
string.replace(old, new, count=-1)Parameters
#old
str
The fragment to replace.new
str
The fragment inserted in place of the old one.count
int, optional
The maximum number of replacements.
Good practices
#- You can chain several
replace()calls, but for many replacements a dictionary with a loop, orstr.translate(), will be more readable. - For case-insensitive replacements, use
re.sub()with there.IGNORECASEflag.
Related entries
#Spotted a mistake or missing an example? Write to us.