If I have a string "knockknock", and use the string method replace

s = "knockknock"
s = s.replace("knock", "bam")
s
"bambam"

it replaces both occurences of the substring at once. Is it possible to replace each substring individually as in ("bamknock", "knockbam")?

A little playful ...

s = "knockknock"
s2 = s.replace("knock", "bam", 1)
print s2

s3 =  s.replace("knock", "bam")
print s3

s4 = s3.replace("bam", "knock", 1)
print s4

# combine s3 and s4 action
s5 = s.replace("knock", "bam").replace("bam", "knock", 1)
print s5

""" my result -->
bamknock
bambam
knockbam
knockbam
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.