Thursday, September 21, 2023
HomeAcademicReplacing Characters within string in Python

Replacing Characters within string in Python

Characters in Python are treated as strings of length one and often considered as sub-string. One can use string literal in python either by using single quote or double quote. For example using value “DataSagar” can be used as ‘DataSagar’. In an example shown below, string1 and string2 both way is possible.

string1 = 'Zero To Hero in Python DataSagar'
string2 = "Zero To Hero in Python DataSagar"

In case of replacing specific character in Python can be done by .replace(character_to_replace, replace_by) method.

string = "Zero To Hero in Python DataSagar"

Output: ZAro To HAro in Python DataSagar

Main thing to understand over here is that .replace() method can be used while string manipulation on the way but doesn’t change the original string. Printing the string again using print() method will give the original value.


Output: Zero To Hero in Python DataSagar

To remove a character from string use .replace() method with underscore ” _” value inreplace_byparameter.


output: ero To Hero in Python DataSagar

To get all the lessons on what can be done with String in Python, Keep tracking #StringInPython in our blog.

The author of this blog post is a technology fellow, an IT entrepreneur, and Educator in Kathmandu Nepal. With his keen interest in Data Science and Business Intelligence, he writes on random topics occasionally in the DataSagar blog.
- Advertisment -

Most Popular