Replacing substrings in a string
In Python, to replace one substring with another in a string, use the replace()
method:
replace(old, new)
- substring old
is replaced by new
;
replace(old, new, num)
- parameter num
shows how many occurrences of substring old
replaced by new
>.
Example
phone = "+1-234-567-89-10"
# hyphens are changed to spaces
edited_phone = phone.replace("-", " ")
print(edited_phone) # +1 234 567 89 10
# hyphens are removed
edited_phone = phone.replace("-", "")
print(edited_phone) # +12345678910
# only the first hyphen changes
edited_phone = phone.replace("-", "", 1)
print(edited_phone) # +1234-567-89-10