Python – Replace given character in a String

Replace given Character in a String

To replace all the occurrences of a given character in a string with a replacement character in Python, use String.replace() method. Call replace() method on the given string, and pass the search character, and replacement character as arguments to the replace() method.


The syntax to replace the character search in the string x with the replacement character replacement is

x.replace(search, replacement)

Search and replacement characters can be specified as string literals.


In the following program, we will take a string in name variable, and replace all the occurrences of the search character 'a' with the replacement character 'p'.

Python Program

x= 'banana'
search = 'a'
replacement = 'p'

output = x.replace(search, replacement)
print(f'Input string  : {x}')
print(f'Output string : {output}')


Input string  : banana
Output string : bpnpnp


In this tutorial of Python Examples, we learned how to replace all the occurrences of a character by a replacement character, with examples.