Replacing substrings within a string is another common string manipulation task in Python. Python provides a built-in method called replace() that can be used to replace all occurrences of a substring within a given string.
The replace() method takes two arguments: the substring to be replaced, and the substring to replace it with. Here is an example:
string = "The quick brown fox jumps over the lazy dog."old_substring = "brown"new_substring = "red"new_string = string.replace(old_substring, new_substring)print(new_string) # Output: "The quick red fox jumps over the lazy dog." |
In this example, the replace() method is used to replace all occurrences of the substring "brown" with the substring "red" within the string "The quick brown fox jumps over the lazy dog." The method returns a new string with the replacements made.
You can also use the replace() method to remove a substring from a string by replacing it with an empty string. For example:
string = "Hello, World!"substring = ", "new_string = string.replace(substring, "")print(new_string) # Output: "HelloWorld!" |
In this example, the replace() method is used to remove the substring ", " from the string "Hello, World!" by replacing it with an empty string.
The replace() method is a powerful tool for performing string manipulation tasks such as replacing or removing substrings within a string. You can use it to perform various text processing tasks such as cleaning up data, formatting text, and more.