In this tutorial, we will be discussing the Python string method str.replace(). This is a built-in function in Python that allows you to replace parts of a string with some other string. It’s an incredibly useful tool when dealing with text manipulation.
Usage
The syntax for using the str.replace() method is as follows:
str.replace(old, new[, count])
- old: This is the old substring you want to replace.
- new: This is the new substring which would replace the old substring.
- count (optional): If this optional argument count is given, only the first ‘count’ occurrences are replaced.
Tutorial: Using str.replace()
To illustrate how to use this function, let’s consider a simple example:
<script> string = "Hello World" new_string = string.replace("World", "Everyone") print(new_string) </script>
In this example, we have a string “Hello World”. We then call the replace() method on this string and pass in two arguments: “World” and “Everyone”. The output of this code will be “Hello Everyone”.
Using Count Parameter in str.replace()
The count parameter can limit the number of replacements. Let’s see an example:
<script> string = "I love apples. I love oranges. I love bananas." new_string = string.replace("I love", "You hate", 2) print(new_string) </script>
In this example, the replace() method will only replace the first two occurrences of “I love” with “You hate”. So, the output will be: “You hate apples. You hate oranges. I love bananas.”
Conclusion
The str.replace() function is a powerful tool for manipulating strings in Python. It’s simple to use and can handle most of your text replacement needs.