In Python, you can find and replace a substring within a string using the replace() method. The replace() method takes two arguments: the first argument is the substring to be replaced, and the second argument is the replacement string.
Here's an example of finding and replacing a substring within a string using the replace() method:
text = "This is a sentence with the word 'apple' in it."# Replace 'apple' with 'orange'new_text = text.replace("apple", "orange")# Print the new stringprint(new_text) |
Output:
This is a sentence with the word 'orange' in it. |
In this example, we have a string text with the word 'apple' in it. We use the replace() method to replace 'apple' with 'orange' in the string, and assign the resulting new string to the variable new_text. We then print the new string to the console.
Note that the replace() method returns a new string with the replacements made, but does not modify the original string. If you want to modify the original string, you can reassign the result of the replace() method to the original string variable.
Here's an example of replacing all occurrences of a substring within a string:
text = "This is a sentence with multiple 'apple's in it."# Replace all occurrences of 'apple' with 'orange'new_text = text.replace("apple", "orange")# Print the new stringprint(new_text) |
Output:
This is a sentence with multiple 'orange's in it. |
In this example, we have a string text with multiple occurrences of the word 'apple'. We use the replace() method to replace all occurrences of 'apple' with 'orange' in the string, and assign the resulting new string to the variable new_text. We then print the new string to the console.