Join Regular Classroom : Visit ClassroomTech

Python String – replace() method

It is a method in python that replaces any given character, phrase or word by a new character, phrase or word. It replaces all the phrases or words if no count is mentioned. The count here determines mow may occurrences of that value shall be replaced.

Syntax:

string.replace(existing_value, new_value, count)

Example 1:

s = “I love to code and sleep
x = s.replace(“sleep“, “eat“)
print(x)

Output:

I love to code and eat

Explanation:

Here the word “sleep” in the string is replaced by the “eat”.

Example 2:

s = “I love to eat, eat, eat and eat
x = s.replace(“eat“, “code“, 3)
print(x)

Output:

I love to code, code, code and eat

Explanation:

Here it particularly replaced first 3 occurrences of the word “eat” by “code”.

You Missed
Also Checkout