Python string replace method explanation with example:
replace is an important method defined in the string class. We can use this method to replace sub-string in a given string. This method returns a new string by replacing all occurrences of a given string by a different string.
In this post, we will learn how to use string replace with example.
replace method syntax:
Below is the syntax of replace:
given_str.replace(old_str, new_str[, count])
- given_str is the original string.
- old_str is the substring that we want to replace in given_str.
- new_str is the new substring that we want to replace old_str with.
- count is the number of replacements we need. This is an optional value. If the value of count is not given, it replaces all old_str with new_str.
This method creates a new string and returns that.
Example of replace:
Let’s take an example on how to use replace.
given_str = 'hello world hello world hello world' new_str = given_str.replace('hello', 'world') print(new_str)
Here, given_str is the given string and we are using replace on this string to replace all hello with world.
If you run this program, it will print the below output:
world world world world world world
replace with count:
Let’s use the last variable count to limit the replacement.
given_str = 'hello world hello world hello world' new_str = given_str.replace('hello', 'world', 1) print(new_str)
Here, we are passing 1 for count. So, it is replacing only the first hello with world. If you run this program, it will print the below output:
world world hello world hello world
As you can see here, it is replacing only the first hello word with world.