Skip to content

Python replace character in string | Example code

  • by

Use the string replaces() method to replace characters in a given string using Python programming. This method will replace all occurrences of a character with a new character.

string.replace(old, new, count)

The count is Optional Parameters used to a number of times you want to replace the old char (substring) with the new char.

Python replace character in the string example

Simple example code.

Replace all the occurrences of the old char are replaced with the new char.

a_string = "aba abc abd"

a_string = a_string.replace("a", "b")

print(a_string)

Output:

Python replace character in string

Replace the two first occurrences of the Character

a_string = "aba abc abd"

a_string = a_string.replace("a", "b",2)

print(a_string)

Output: bbb abc abd

Do comment if you have any doubts and suggestions on this Python char string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading