Home Academic Replacing Characters within string in Python

Replacing Characters within string in Python

0

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"
print(string.replace(e,A))

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.

print(string)

Output: Zero To Hero in Python DataSagar

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

.replace(Z,_)

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.

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here