Search⌘ K
AI Features

Solution: Replace All Occurrences of a Character in a String

Understand how to locate and replace every instance of a specific character in a string. Learn to use Python's find, count, and replace methods with control over the number of replacements. This lesson helps you master string manipulation techniques essential for text processing tasks.

We'll cover the following...

The solution to the problem of finding and replacing all occurrences of a specific character in a string is given below.

Solution

Python 3.8
s = "The Terrible Tiger Tore The Towel"
a = 'T'
b = 't'
pos = s.find(a, 0)
print(pos)
pos = s.find(a, pos + 1)
print(pos)
pos = s.find(a, pos + 1)
print(pos)
pos = s.find(a, pos + 1)
print(pos)
pos = s.find(a, pos + 1)
print(pos)
pos = s.find(a, pos + 1)
print(pos)
pos = s.find(a, pos + 1)
print(pos)
c = s.count(a)
s = s.replace(a, b, c)
print(s)
...