Python replace() - How to replace a substring

A Python string is replaced by the replace() like this.

s = 'Python'

t = s.replace('ython', 'HP')

print(t)
# PHP

ython was replaced with HP. The replace() doesn't change the original string. The s is still Python.

s = 'Python'

t = s.replace('ython', 'HP')

print(s)
# Python

print(t)
# PHP

Replacing count

The replace() function takes three parameters.

replace(old, new, count)

The third parameter is optional and the maximum occurrences to replace. If you don't set it, the function replaces all substrings. If the count is 0 or negative integer, the method doesn't replace any substrings.

s = 'AAA AA Store'

t = s.replace('AA', 'BB')

print(t)
# BBA BB Store

If the count parameter is 1, the replace() replaces once.

s = 'AAA AA Store'

t = s.replace('AA', 'BB', 1)

print(t)
# BBA AA Store

Python String

Python Tutorial